gloomberb 0.20.3 → 0.20.4

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 (154) hide show
  1. package/package.json +1 -1
  2. package/src/account/auth-dialog.tsx +17 -0
  3. package/src/api-client/data.ts +6 -0
  4. package/src/api-client/fx-interventions.ts +64 -0
  5. package/src/api-client/index.ts +1 -0
  6. package/src/api-client/release-summaries.ts +21 -0
  7. package/src/app/keybindings/actions.ts +2 -2
  8. package/src/app/pane-runtime/ticker-open-runtime.ts +245 -66
  9. package/src/cli/commands/market.ts +77 -1
  10. package/src/cli/commands/news-search.ts +1 -3
  11. package/src/cli/commands/plugins.ts +27 -5
  12. package/src/cli/commands/system.ts +19 -3
  13. package/src/cli/commands/ticker.ts +60 -19
  14. package/src/cli/index.ts +8 -8
  15. package/src/cli/pane-functions/function-help.ts +3 -3
  16. package/src/cli/report-tables.ts +18 -6
  17. package/src/cli/result.ts +15 -7
  18. package/src/cli/types.ts +2 -0
  19. package/src/components/chart/composite/axis-overlays.tsx +22 -0
  20. package/src/components/chart/composite/composite-chart.tsx +54 -13
  21. package/src/components/chart/composite/event-captions.ts +109 -0
  22. package/src/components/chart/composite/event-guides.ts +74 -0
  23. package/src/components/chart/composite/rasterizer.ts +2 -0
  24. package/src/components/chart/composite/text-renderer.ts +2 -0
  25. package/src/components/chart/composite/types.ts +31 -0
  26. package/src/components/command-bar/layout-items/focused-pane.ts +5 -5
  27. package/src/components/command-bar/routes/root/provider-search.ts +5 -4
  28. package/src/components/command-bar/routes/ticker-search/results.ts +51 -0
  29. package/src/components/command-bar/routes/ticker-search/route.ts +3 -2
  30. package/src/components/layout/detached-pane-shell.tsx +1 -1
  31. package/src/components/layout/floating-pane.tsx +5 -1
  32. package/src/components/layout/pane/footer/index.tsx +21 -14
  33. package/src/components/layout/pane/footer/model.ts +6 -0
  34. package/src/components/layout/shell/action-menu-overlay.tsx +10 -5
  35. package/src/components/layout/shell/active-drag.ts +149 -105
  36. package/src/components/layout/shell/drag/drop-zones.ts +162 -0
  37. package/src/components/layout/shell/drag/index.ts +47 -218
  38. package/src/components/layout/shell/drag/live.ts +10 -3
  39. package/src/components/layout/shell/drag/overlays.tsx +182 -5
  40. package/src/components/layout/shell/drag/runtime.ts +29 -6
  41. package/src/components/layout/shell/drag/shared-edges.ts +156 -0
  42. package/src/components/layout/shell/index.tsx +11 -6
  43. package/src/components/layout/shell/menu.ts +11 -2
  44. package/src/components/layout/shell/native/pointer-runtime.ts +25 -0
  45. package/src/components/layout/shell/native/window-state.ts +2 -2
  46. package/src/components/layout/shell/pane/layers.tsx +71 -7
  47. package/src/components/layout/shell/terminal-pointer-runtime.ts +18 -9
  48. package/src/components/layout/shell/window-mode/index.ts +8 -10
  49. package/src/components/layout/window-edit/mode.ts +39 -7
  50. package/src/components/layout/window-edit/presentation.ts +1 -1
  51. package/src/components/onboarding/onboarding-keyboard.ts +4 -0
  52. package/src/components/onboarding/onboarding-wizard.tsx +8 -3
  53. package/src/components/ui/button.tsx +2 -0
  54. package/src/components/ui/choice-dialog.tsx +1 -0
  55. package/src/components/ui/data-table/index.tsx +4 -3
  56. package/src/components/ui/list-view.tsx +7 -12
  57. package/src/components/ui/loading.tsx +10 -3
  58. package/src/components/ui/menu.tsx +6 -2
  59. package/src/components/ui/quote.ts +14 -1
  60. package/src/data/config/layout.ts +5 -2
  61. package/src/docs/snapshot.json +29 -5
  62. package/src/i18n/es.ts +9 -8
  63. package/src/i18n/ja.ts +9 -8
  64. package/src/i18n/ko.ts +9 -8
  65. package/src/i18n/zh-cn.ts +9 -8
  66. package/src/i18n/zh-tw.ts +9 -8
  67. package/src/layout/pane-manager/floating-actions.ts +17 -0
  68. package/src/layout/pane-manager/floating-stack.ts +187 -0
  69. package/src/layout/pane-manager/floating.ts +4 -2
  70. package/src/layout/pane-manager/gridlock.ts +5 -1
  71. package/src/layout/pane-manager/index.ts +11 -0
  72. package/src/layout/pane-manager/layout-state.ts +10 -3
  73. package/src/market-data/futures-board.ts +46 -1
  74. package/src/market-data/futures-contract.ts +12 -3
  75. package/src/market-data/fx-interventions.ts +270 -0
  76. package/src/news/news-model.ts +44 -2
  77. package/src/plugins/builtin/alerts/cli.ts +4 -4
  78. package/src/plugins/builtin/alerts/format.ts +1 -2
  79. package/src/plugins/builtin/alerts/headless.ts +1 -2
  80. package/src/plugins/builtin/alerts/move-checks.ts +12 -6
  81. package/src/plugins/builtin/alerts/move.ts +30 -9
  82. package/src/plugins/builtin/alerts/pane.tsx +0 -2
  83. package/src/plugins/builtin/alerts/storage.ts +4 -2
  84. package/src/plugins/builtin/alerts/types.ts +12 -0
  85. package/src/plugins/builtin/changelog/index.tsx +292 -101
  86. package/src/plugins/builtin/changelog/versions.ts +293 -0
  87. package/src/plugins/builtin/chart-composer/intervention-events.ts +105 -0
  88. package/src/plugins/builtin/chart-composer/pane.tsx +21 -7
  89. package/src/plugins/builtin/chat/message/render-state.ts +2 -5
  90. package/src/plugins/builtin/cloud/askg/attached-pane.tsx +10 -5
  91. package/src/plugins/builtin/cloud/askg/controller.ts +141 -5
  92. package/src/plugins/builtin/cloud/askg/executor.ts +113 -4
  93. package/src/plugins/builtin/cloud/askg/manifest.ts +28 -13
  94. package/src/plugins/builtin/cloud/askg/model.ts +14 -4
  95. package/src/plugins/builtin/cloud/askg/pane.tsx +70 -46
  96. package/src/plugins/builtin/cloud/askg/turn-parts.tsx +70 -0
  97. package/src/plugins/builtin/cloud/terminal-relay/engine.ts +50 -130
  98. package/src/plugins/builtin/cloud/terminal-relay/policy.ts +327 -7
  99. package/src/plugins/builtin/cloud/terminal-relay/prompts.tsx +2 -1
  100. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +47 -6
  101. package/src/plugins/builtin/commodities-energy/index.tsx +1 -3
  102. package/src/plugins/builtin/commodities-energy/view-state.ts +3 -0
  103. package/src/plugins/builtin/cot/headless.ts +14 -2
  104. package/src/plugins/builtin/earnings/index.tsx +2 -2
  105. package/src/plugins/builtin/futures/index.tsx +25 -4
  106. package/src/plugins/builtin/futures/model.ts +28 -32
  107. package/src/plugins/builtin/futures/series.ts +4 -3
  108. package/src/plugins/builtin/futures/table.tsx +16 -9
  109. package/src/plugins/builtin/futures/use-board-terms.ts +3 -3
  110. package/src/plugins/builtin/help/index.tsx +3 -3
  111. package/src/plugins/builtin/help/keybindings-editor.tsx +18 -4
  112. package/src/plugins/builtin/layout-manager/index.tsx +8 -8
  113. package/src/plugins/builtin/news/headless.ts +2 -2
  114. package/src/plugins/builtin/news/index.tsx +3 -3
  115. package/src/plugins/builtin/perps/markets-section.tsx +5 -2
  116. package/src/plugins/builtin/plugin-marketplace/pane.tsx +11 -11
  117. package/src/plugins/builtin/portfolio-list/summary/index.tsx +3 -1
  118. package/src/plugins/builtin/research/event-model.ts +9 -1
  119. package/src/plugins/builtin/research/event-sources.ts +22 -0
  120. package/src/plugins/builtin/research/headless.ts +3 -3
  121. package/src/plugins/builtin/shared/cloud-upgrade.ts +27 -3
  122. package/src/plugins/builtin/ticker-detail/overview/components.tsx +54 -5
  123. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +28 -13
  124. package/src/plugins/builtin/ticker-detail/pane.tsx +7 -2
  125. package/src/plugins/installer.ts +45 -0
  126. package/src/remote/resources.ts +12 -1
  127. package/src/remote/schema.ts +1 -0
  128. package/src/remote/semantic-helpers.ts +29 -1
  129. package/src/remote/semantic-tree.tsx +32 -15
  130. package/src/renderers/cloudflare/worker.ts +16 -1
  131. package/src/renderers/dom/styles.css +40 -6
  132. package/src/renderers/share/layout-view.tsx +1 -1
  133. package/src/sources/gloomberb-cloud/news.ts +35 -12
  134. package/src/state/opening-ticker-panes.ts +47 -0
  135. package/src/test-support/cli-context.ts +2 -0
  136. package/src/test-support/preload.ts +4 -1
  137. package/src/tickers/instrument-kind.ts +23 -3
  138. package/src/types/config.ts +5 -0
  139. package/src/types/context-menu.ts +2 -0
  140. package/src/types/plugin-commands.ts +140 -0
  141. package/src/types/plugin-context.ts +125 -0
  142. package/src/types/plugin-contributions.ts +55 -0
  143. package/src/types/plugin-definition.ts +234 -0
  144. package/src/types/plugin-notifications.ts +38 -0
  145. package/src/types/plugin-pane-settings.ts +114 -0
  146. package/src/types/plugin-pane-templates.ts +160 -0
  147. package/src/types/plugin-panes.ts +221 -0
  148. package/src/types/plugin-reports.ts +35 -0
  149. package/src/types/plugin-shared.ts +14 -0
  150. package/src/types/plugin-state.ts +71 -0
  151. package/src/types/plugin.ts +14 -1169
  152. package/src/ui/index.tsx +14 -3
  153. package/src/updater/github-releases.ts +23 -0
  154. package/src/utils/cli-output.ts +22 -9
@@ -0,0 +1,187 @@
1
+ import type { FloatingPaneEntry, LayoutConfig } from "../../types/config";
2
+ import { compactFloatingZ, maxFloatingZ } from "./floating";
3
+ import { detachPane, finalizeLayout } from "./layout-state";
4
+
5
+ /**
6
+ * Floating windows stacked as tabs: the members share a `stack` key and one
7
+ * rect, in the order the layout lists them, and the one in front (highest z,
8
+ * the later one of equals) is the tab shown. Raising a member (a click on its
9
+ * tab, focus) shows it; moving or resizing the stack moves every member
10
+ * (`floatAtRect`). A key with one member left is dropped when the layout is
11
+ * finalized.
12
+ */
13
+
14
+ /** The members of the stack `instanceId` floats in, in tab order; empty when it floats alone. */
15
+ export function floatingStackMembers(floating: readonly FloatingPaneEntry[], instanceId: string): FloatingPaneEntry[] {
16
+ const entry = floating.find((candidate) => candidate.instanceId === instanceId);
17
+ if (!entry?.stack) return [];
18
+ const members = floating.filter((candidate) => candidate.stack === entry.stack);
19
+ return members.length > 1 ? members : [];
20
+ }
21
+
22
+ /** The member a stack shows: the one in front. */
23
+ function shownStackMember(members: readonly FloatingPaneEntry[]): FloatingPaneEntry | undefined {
24
+ let shown: FloatingPaneEntry | undefined;
25
+ for (const member of members) {
26
+ if (!shown || (member.zIndex ?? 50) >= (shown.zIndex ?? 50)) shown = member;
27
+ }
28
+ return shown;
29
+ }
30
+
31
+ /**
32
+ * Every floating stack, by the pane it shows, with its tabs in order. A list
33
+ * sorted some other way (front to back) takes the layout's list as `order`.
34
+ */
35
+ export function floatingStacks(
36
+ floating: readonly FloatingPaneEntry[],
37
+ order?: readonly { instanceId: string }[],
38
+ ): Map<string, string[]> {
39
+ const rank = order ? new Map(order.map((entry, index) => [entry.instanceId, index])) : null;
40
+ const byKey = new Map<string, FloatingPaneEntry[]>();
41
+ for (const entry of floating) {
42
+ if (!entry.stack) continue;
43
+ const members = byKey.get(entry.stack) ?? [];
44
+ members.push(entry);
45
+ byKey.set(entry.stack, members);
46
+ }
47
+ const stacks = new Map<string, string[]>();
48
+ for (const members of byKey.values()) {
49
+ if (members.length < 2) continue;
50
+ const tabs = rank ? [...members].sort((a, b) => (rank.get(a.instanceId) ?? 0) - (rank.get(b.instanceId) ?? 0)) : members;
51
+ stacks.set(shownStackMember(members)!.instanceId, tabs.map((member) => member.instanceId));
52
+ }
53
+ return stacks;
54
+ }
55
+
56
+ /**
57
+ * Floating entries as a saved layout may hold them, made whole: a `stack`
58
+ * key that is not a non-empty string, or that one entry alone has, is
59
+ * dropped, and every member of a stack takes the rect of the tab it shows.
60
+ * A client that does not know stacks keeps the key but draws each member as
61
+ * a window of its own, so it may have moved them apart.
62
+ */
63
+ export function alignFloatingStacks<T extends FloatingPaneEntry>(floating: readonly T[]): T[] {
64
+ const byKey = new Map<string, T[]>();
65
+ for (const entry of floating) {
66
+ if (typeof entry.stack !== "string" || entry.stack.length === 0) continue;
67
+ byKey.set(entry.stack, [...(byKey.get(entry.stack) ?? []), entry]);
68
+ }
69
+ const rects = new Map<string, Pick<FloatingPaneEntry, "x" | "y" | "width" | "height">>();
70
+ for (const [key, members] of byKey) {
71
+ if (members.length < 2) continue;
72
+ const { x, y, width, height } = shownStackMember(members)!;
73
+ rects.set(key, { x, y, width, height });
74
+ }
75
+ return floating.map((entry) => {
76
+ const rect = typeof entry.stack === "string" ? rects.get(entry.stack) : undefined;
77
+ if (rect) return { ...entry, ...rect };
78
+ if (!("stack" in entry)) return entry;
79
+ const { stack: _stack, ...rest } = entry;
80
+ return rest as T;
81
+ });
82
+ }
83
+
84
+ /** The floating panes behind the tab their stack shows. */
85
+ export function hiddenFloatingTabIds(floating: readonly FloatingPaneEntry[]): Set<string> {
86
+ const hidden = new Set<string>();
87
+ for (const [shown, members] of floatingStacks(floating)) {
88
+ for (const id of members) if (id !== shown) hidden.add(id);
89
+ }
90
+ return hidden;
91
+ }
92
+
93
+ /**
94
+ * A key no stack has yet, for a stack `instanceId` starts: its own id unless
95
+ * that is taken. A tab pulled out of a stack leaves the key with the tabs
96
+ * that stay, so the id of the window that started a stack may still name it.
97
+ */
98
+ function newStackKey(floating: readonly FloatingPaneEntry[], instanceId: string): string {
99
+ const taken = new Set(floating.flatMap((entry) => (entry.stack ? [entry.stack] : [])));
100
+ let key = instanceId;
101
+ for (let n = 2; taken.has(key); n += 1) key = `${instanceId}#${n}`;
102
+ return key;
103
+ }
104
+
105
+ /**
106
+ * `draggedId` as the last tab of the floating window `targetId` (or its
107
+ * stack), shown, at its rect. The dragged pane leaves wherever it was: the
108
+ * dock, another stack, a floating spot of its own.
109
+ */
110
+ export function stackFloatingOnto(layout: LayoutConfig, draggedId: string, targetId: string): LayoutConfig {
111
+ if (draggedId === targetId) return layout;
112
+ const target = layout.floating.find((entry) => entry.instanceId === targetId);
113
+ if (!target) return layout;
114
+ const key = target.stack ?? newStackKey(layout.floating, target.instanceId);
115
+ const base = detachPane(layout, draggedId);
116
+ const floating = base.floating.map((entry) => (entry.instanceId === targetId ? { ...entry, stack: key } : entry));
117
+ floating.push({
118
+ instanceId: draggedId,
119
+ x: target.x,
120
+ y: target.y,
121
+ width: target.width,
122
+ height: target.height,
123
+ zIndex: maxFloatingZ(layout) + 1,
124
+ stack: key,
125
+ });
126
+ return finalizeLayout({ ...base, floating: compactFloatingZ(floating) });
127
+ }
128
+
129
+ /** `instanceId` out of its floating stack, where it is, the others left as they are. */
130
+ export function unstackFloating(layout: LayoutConfig, instanceId: string): LayoutConfig {
131
+ const entry = layout.floating.find((candidate) => candidate.instanceId === instanceId);
132
+ if (!entry?.stack) return layout;
133
+ return finalizeLayout({
134
+ ...layout,
135
+ floating: layout.floating.map((candidate) => {
136
+ if (candidate.instanceId !== instanceId) return candidate;
137
+ const { stack: _stack, ...rest } = candidate;
138
+ return rest;
139
+ }),
140
+ });
141
+ }
142
+
143
+ export type FloatingSplitSide = "left" | "right" | "top" | "bottom";
144
+
145
+ /** The two halves of `rect` a split on `side` makes: the dropped window's, then the target's. */
146
+ export function floatingSplitRects(
147
+ rect: { x: number; y: number; width: number; height: number },
148
+ side: FloatingSplitSide,
149
+ ): [{ x: number; y: number; width: number; height: number }, { x: number; y: number; width: number; height: number }] {
150
+ const { x, y, width, height } = rect;
151
+ if (side === "left" || side === "right") {
152
+ const half = width / 2;
153
+ const left = { x, y, width: half, height };
154
+ const right = { x: x + half, y, width: width - half, height };
155
+ return side === "left" ? [left, right] : [right, left];
156
+ }
157
+ const half = height / 2;
158
+ const top = { x, y, width, height: half };
159
+ const bottom = { x, y: y + half, width, height: height - half };
160
+ return side === "top" ? [top, bottom] : [bottom, top];
161
+ }
162
+
163
+ /**
164
+ * `draggedId` beside the floating window `targetId` on `side`, sharing its
165
+ * rect: each takes half, edge to edge, so their shared edge resizes both.
166
+ * The target's stack, if it is one, keeps its tabs and takes its half whole.
167
+ */
168
+ export function splitFloating(layout: LayoutConfig, draggedId: string, targetId: string, side: FloatingSplitSide): LayoutConfig {
169
+ if (draggedId === targetId) return layout;
170
+ const target = layout.floating.find((entry) => entry.instanceId === targetId);
171
+ if (!target) return layout;
172
+ const [dropped, kept] = floatingSplitRects(target, side);
173
+ const base = finalizeLayout(detachPane(layout, draggedId));
174
+ const resized = finalizeLayout({
175
+ ...base,
176
+ floating: base.floating.map((entry) => (
177
+ entry.instanceId === targetId || (target.stack && entry.stack === target.stack) ? { ...entry, ...kept } : entry
178
+ )),
179
+ });
180
+ return finalizeLayout({
181
+ ...resized,
182
+ floating: compactFloatingZ([
183
+ ...resized.floating,
184
+ { instanceId: draggedId, ...dropped, zIndex: maxFloatingZ(resized) + 1 },
185
+ ]),
186
+ });
187
+ }
@@ -89,9 +89,11 @@ const FLOATING_PANE_BASE_Z = 50;
89
89
  * pair at `under` and `over`: on the desktop the landing preview under the
90
90
  * pane on the move (lifted to `over` while it is over a target, or its outline
91
91
  * when it was docked); in the terminal, which cannot see through a pane, the
92
- * docked pane's outline under the landing outline.
92
+ * docked pane's outline under the landing outline. The drop targets a move
93
+ * offers (the target on the pane under the pointer, the strips along the
94
+ * window's edges) sit over both, at `targets`.
93
95
  */
94
- export const SHELL_DRAG_Z = { under: 95, over: 96 } as const;
96
+ export const SHELL_DRAG_Z = { under: 95, over: 96, targets: 97 } as const;
95
97
 
96
98
  /** The lowest of the shell's fixed overlays over every pane. */
97
99
  const SHELL_PREVIEW_Z = SHELL_DRAG_Z.under;
@@ -1,5 +1,6 @@
1
1
  import type { DockLayoutNode, FloatingPaneEntry, LayoutConfig } from "../../types/config";
2
2
  import { buildDockStack, isDockStack } from "./dock-stack";
3
+ import { floatingStacks, hiddenFloatingTabIds } from "./floating-stack";
3
4
  import type { AppNotificationRequest } from "../../types/plugin";
4
5
  import {
5
6
  boundsForRects,
@@ -165,7 +166,10 @@ export function gridlockAllPanes(
165
166
  const dockedRects: GridlockRect[] = leaves.map((leaf) => ({ instanceId: leaf.instanceId, ...leaf.rect }));
166
167
  // A stack is tiled as the tab it shows and keeps its other tabs.
167
168
  const stacks = new Map(leaves.flatMap((leaf) => (leaf.stack ? [[leaf.instanceId, leaf.stack] as const] : [])));
168
- const floatingRects: GridlockRect[] = visibleLayout.floating.map((entry) => ({
169
+ // A floating stack is tiled as the tab it shows, and keeps its tabs as a docked stack.
170
+ for (const [shown, members] of floatingStacks(visibleLayout.floating)) stacks.set(shown, members);
171
+ const hiddenTabs = hiddenFloatingTabIds(visibleLayout.floating);
172
+ const floatingRects: GridlockRect[] = visibleLayout.floating.filter((entry) => !hiddenTabs.has(entry.instanceId)).map((entry) => ({
169
173
  instanceId: entry.instanceId,
170
174
  x: entry.x,
171
175
  y: entry.y,
@@ -54,6 +54,17 @@ export {
54
54
  swapPanes,
55
55
  } from "./docking";
56
56
 
57
+ export {
58
+ floatingSplitRects,
59
+ floatingStackMembers,
60
+ floatingStacks,
61
+ hiddenFloatingTabIds,
62
+ splitFloating,
63
+ stackFloatingOnto,
64
+ unstackFloating,
65
+ type FloatingSplitSide,
66
+ } from "./floating-stack";
67
+
57
68
  export { restoreHiddenPanes } from "./hidden-panes";
58
69
  export {
59
70
  removeFloatingPanes,
@@ -27,14 +27,21 @@ function normalizeFloatingEntries(layout: LayoutConfig): FloatingPaneEntry[] {
27
27
  const dockedIds = new Set(getDockedInstanceIds(layout.dockRoot));
28
28
  const detachedIds = new Set((layout.detached ?? []).map((entry) => entry.instanceId));
29
29
  const seen = new Set<string>();
30
- return layout.floating
30
+ const kept = layout.floating
31
31
  .filter((entry) => !dockedIds.has(entry.instanceId) && !detachedIds.has(entry.instanceId))
32
32
  .filter((entry) => {
33
33
  if (seen.has(entry.instanceId)) return false;
34
34
  seen.add(entry.instanceId);
35
35
  return true;
36
- })
37
- .map((entry) => ({ ...entry }));
36
+ });
37
+ // A floating stack left with one tab is a window of its own again.
38
+ const stackSizes = new Map<string, number>();
39
+ for (const entry of kept) if (entry.stack) stackSizes.set(entry.stack, (stackSizes.get(entry.stack) ?? 0) + 1);
40
+ return kept.map((entry) => {
41
+ if (!entry.stack || (stackSizes.get(entry.stack) ?? 0) > 1) return { ...entry };
42
+ const { stack: _stack, ...rest } = entry;
43
+ return rest;
44
+ });
38
45
  }
39
46
 
40
47
  function normalizeDetachedEntries(layout: LayoutConfig) {
@@ -173,6 +173,41 @@ export const FUTURES_SECTOR_ORDER: FuturesSector[] = [
173
173
  "currencies",
174
174
  ];
175
175
 
176
+ /**
177
+ * The board's groups a reader names by a word: its sectors in any of their
178
+ * forms, and the two the Agriculture sector holds that traders name apart,
179
+ * the softs (grown, not mined, and traded in New York) and the grains with
180
+ * their soybean products.
181
+ */
182
+ const FUTURES_GROUP_WORDS: ReadonlyArray<{ words: readonly string[]; label: string; matches: (contract: FuturesContract) => boolean }> = [
183
+ { words: ["softs", "soft", "soft commodities"], label: "softs", matches: (contract) => ["KC", "SB", "CC", "CT", "OJ"].includes(contract.code) },
184
+ { words: ["grains", "grain", "grains and oilseeds"], label: "grains", matches: (contract) => ["ZC", "ZS", "ZM", "ZL", "ZW", "KE"].includes(contract.code) },
185
+ { words: ["agriculture", "agricultural", "ags", "ag", "agri"], label: "agriculture", matches: (contract) => contract.sector === "agriculture" },
186
+ { words: ["metals", "metal"], label: "metals", matches: (contract) => contract.sector === "metals" },
187
+ { words: ["energy", "energies"], label: "energy", matches: (contract) => contract.sector === "energy" },
188
+ { words: ["livestock", "meats"], label: "livestock", matches: (contract) => contract.sector === "livestock" },
189
+ { words: ["currencies", "currency", "fx"], label: "currencies", matches: (contract) => contract.sector === "currencies" },
190
+ { words: ["rates", "interest rates", "treasuries"], label: "rates", matches: (contract) => contract.sector === "rates" },
191
+ { words: ["equity index", "equity indices", "indices", "stock index", "stock indices"], label: "equity index",
192
+ matches: (contract) => contract.sector === "equity-index" },
193
+ { words: ["equity sectors", "sector futures"], label: "equity sectors", matches: (contract) => contract.sector === "equity-sectors" },
194
+ ];
195
+
196
+ /**
197
+ * The rows a group word stands for (`FUT softs`, `FUT agriculture`), or null
198
+ * for any other search. A sector's word lists that sector alone: "energy"
199
+ * is the energy futures, not the S&P Energy sector future beside them.
200
+ */
201
+ export function futuresGroupFilter(query: string): ((contract: FuturesContract) => boolean) | null {
202
+ const typed = query.trim().toLowerCase().replace(/\s+/g, " ");
203
+ return FUTURES_GROUP_WORDS.find((group) => group.words.includes(typed))?.matches ?? null;
204
+ }
205
+
206
+ /** The group words a contract is found by, as a catalog search reads them: KC is softs and agriculture. */
207
+ export function futuresGroupTags(contract: FuturesContract): string[] {
208
+ return FUTURES_GROUP_WORDS.filter((group) => group.matches(contract)).map((group) => group.label);
209
+ }
210
+
176
211
  export function getContractsBySector(): Map<FuturesSector, FuturesContract[]> {
177
212
  const map = new Map<FuturesSector, FuturesContract[]>();
178
213
  for (const sector of FUTURES_SECTOR_ORDER) {
@@ -235,7 +270,17 @@ export function futuresBoardContract(value: unknown): FuturesContract | null {
235
270
  return BY_SYMBOL.get(typed(value)) ?? futuresContractByCode(value);
236
271
  }
237
272
 
238
- const nameWords = (text: string) => text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
273
+ /**
274
+ * A contract's name as a reader may type it, with its number marked any way:
275
+ * "SUGAR NO. 11", the CFTC's name, and "Sugar #11", the board's, are both
276
+ * "sugar 11". Lower case, "No."/"Nr." before a number and "#" dropped,
277
+ * spaces collapsed.
278
+ */
279
+ export function futuresNameKey(text: string): string {
280
+ return text.toLowerCase().replace(/\b(?:no|nr)\.?\s*(?=\d)/g, " ").replace(/#/g, " ").replace(/\s+/g, " ").trim();
281
+ }
282
+
283
+ const nameWords = (text: string) => futuresNameKey(text).split(/[^a-z0-9]+/).filter(Boolean);
239
284
 
240
285
  /**
241
286
  * The item a typed name means: every word of it starts a word of the item's
@@ -325,8 +325,12 @@ export type FuturesChangeTerms = Pick<FuturesContractTermsPayload, "settlement">
325
325
  * is confirmed: Wednesday's 7,720.50 close at 23:18 UTC, "+14 vs Wed 4 Nov
326
326
  * close", never +137.75 from Tuesday's settlement, two sessions. At any
327
327
  * other time the terms are behind and nothing dates it (null);
328
- * - without a settlement in the terms, or once the move's own session has
329
- * settled, is the session before's close, which nothing else checks.
328
+ * - once the move's own session has settled, is the session before's
329
+ * settlement when the quote closes on its own (Gloom Cloud then measures
330
+ * it from the one before: CC=F's 5,155 on Fri 6 Nov 2026, "-26 vs Thu 5
331
+ * Nov settle"), and otherwise the session before's close;
332
+ * - without a settlement in the terms, is the session before's close, which
333
+ * nothing else checks.
330
334
  * On a venue without a calendar only a settlement is named. Null without a
331
335
  * session date, a move or terms.
332
336
  */
@@ -350,10 +354,15 @@ export function futuresChangeBasis(
350
354
  if (settled && settled.date <= session && Math.abs(reference - settled.price) <= settlementTolerance(terms.spec?.tick, settled.price)) {
351
355
  return { kind: "settle", session: settled.date };
352
356
  }
357
+ const sameContract = !!move.month && terms.deliveryMonth?.slice(0, 7) === move.month;
353
358
  if (settled && previous && settled.date === previous) {
354
- const sameContract = !!move.month && terms.deliveryMonth?.slice(0, 7) === move.month;
355
359
  return sameContract && Number.isFinite(move.price) ? { kind: "settle", session: previous, from: settled.price } : null;
356
360
  }
361
+ // The move's own session settled, and the quote closes on that settlement: Gloom Cloud measures it from the one before.
362
+ if (settled && previous && settled.date === session && sameContract
363
+ && Math.abs(move.price - settled.price) <= settlementTolerance(terms.spec?.tick, settled.price)) {
364
+ return { kind: "settle", session: previous };
365
+ }
357
366
  if (settled && previous && settled.date < previous) return print?.overnight && print.tradeDate === moveDate ? { kind: "close", session: previous } : null;
358
367
  return previous ? { kind: "close", session: previous } : null;
359
368
  }
@@ -0,0 +1,270 @@
1
+ import { apiClient } from "../api-client";
2
+ import type { FxInterventionDay, FxInterventionMonth, FxInterventionRun, FxInterventionsPayload } from "../api-client/fx-interventions";
3
+ import { currencyPairSpelling } from "../utils/currency-pair";
4
+ import { logFailure } from "../utils/log-failure";
5
+
6
+ /**
7
+ * Japan's foreign exchange interventions as its Ministry of Finance publishes
8
+ * them: each intervention, from the quarterly releases, and each monthly
9
+ * total, which names no day and no pair until its quarter is released. Shown
10
+ * in `fx` and `history` notes for a yen pair, and on a yen pair's chart.
11
+ */
12
+
13
+ /** The two currencies of a yen pair, as the listing writes them: USD and JPY for USDJPY=X. */
14
+ export interface FxInterventionPair {
15
+ base: string;
16
+ quote: string;
17
+ }
18
+
19
+ /** The side Japan took: it bought yen to hold it up, or sold yen to hold it down. */
20
+ type FxInterventionSide = "yen bought" | "yen sold";
21
+
22
+ /** A total the ministry has reported whose days are not published yet. */
23
+ interface UndatedTotal {
24
+ from: string;
25
+ to: string;
26
+ amountJpy: number;
27
+ releasedOn: string;
28
+ }
29
+
30
+ const DAY_MS = 86_400_000;
31
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
32
+ const CURRENCY_WORDS: Record<string, string> = { USD: "dollars", JPY: "yen", EUR: "euros", DEM: "marks", IDR: "rupiah" };
33
+ const DAYS_KNOWN: ReadonlySet<unknown> = new Set(["all", "partial", "none"]);
34
+
35
+ const isDay = (value: unknown): value is string => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)
36
+ && Number.isFinite(Date.parse(`${value}T00:00:00Z`)) && new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
37
+ const isCode = (value: unknown) => value === null || typeof value === "string" && /^[A-Z]{3}$/.test(value);
38
+ const isAmount = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
39
+ const nextDay = (date: string) => new Date(Date.parse(`${date}T00:00:00Z`) + DAY_MS).toISOString().slice(0, 10);
40
+
41
+ function readsAsDay(day: FxInterventionDay | undefined): boolean {
42
+ return !!day && isDay(day.date) && isAmount(day.amountJpy) && isCode(day.sold) && isCode(day.bought) && typeof day.pair === "string";
43
+ }
44
+
45
+ function readsAsRun(run: FxInterventionRun | undefined): boolean {
46
+ return !!run && isDay(run.from) && isDay(run.to) && run.to >= run.from && Number.isInteger(run.days) && run.days >= 1
47
+ && isAmount(run.amountJpy) && isCode(run.sold) && isCode(run.bought) && typeof run.pair === "string";
48
+ }
49
+
50
+ function readsAsMonth(month: FxInterventionMonth | undefined): boolean {
51
+ return !!month && isDay(month.from) && isDay(month.to) && month.to >= month.from && isAmount(month.amountJpy) && isDay(month.releasedOn)
52
+ && DAYS_KNOWN.has(month.daysKnown) && isAmount(month.undatedAmountJpy) && month.undatedAmountJpy <= month.amountJpy;
53
+ }
54
+
55
+ /**
56
+ * The reply as this app reads it, or null: a reply with a day out of order, a
57
+ * negative or missing amount or a period that ends before it starts is no
58
+ * record, never a guessed one. A server without the route answers 404, which
59
+ * the loader also reads as none.
60
+ */
61
+ export function readFxInterventions(payload: unknown): FxInterventionsPayload | null {
62
+ if (!payload || typeof payload !== "object") return null;
63
+ const record = payload as FxInterventionsPayload;
64
+ if (record.status !== "available" || !Array.isArray(record.days) || !Array.isArray(record.interventions) || !Array.isArray(record.months)
65
+ || !(record.dailyThrough === null || isDay(record.dailyThrough))) return null;
66
+ const inOrder = <T>(entries: readonly T[], date: (entry: T) => string) => entries.every((entry, index) => index === 0 || date(entries[index - 1]!) <= date(entry));
67
+ if (!record.days.every(readsAsDay) || !inOrder(record.days, (day) => day.date)) return null;
68
+ if (!record.interventions.every(readsAsRun) || !inOrder(record.interventions, (run) => run.from)) return null;
69
+ return record.months.every(readsAsMonth) ? record : null;
70
+ }
71
+
72
+ type FxInterventionsClient = Pick<typeof apiClient, "getCloudFxInterventions">;
73
+ const FRESH_MS = 10 * 60_000;
74
+ const RETRY_MS = 60_000;
75
+
76
+ /**
77
+ * A loader of the record from Gloom Cloud: null when it has none (not read
78
+ * yet, an older server) or could not be reached, so a note or a chart marker
79
+ * is left out, never the rate or the chart it goes with. One request serves
80
+ * every caller for ten minutes, a failed one for a minute.
81
+ */
82
+ export function createFxInterventionsLoader(
83
+ client: FxInterventionsClient,
84
+ now: () => number = Date.now,
85
+ ): () => Promise<FxInterventionsPayload | null> {
86
+ let held: { at: number; ttl: number; promise: Promise<FxInterventionsPayload | null> } | null = null;
87
+ return () => {
88
+ const at = now();
89
+ if (held && at - held.at < held.ttl) return held.promise;
90
+ const promise = client.getCloudFxInterventions()
91
+ .then(readFxInterventions, logFailure("market-data.fx-interventions", "Japan's intervention record could not be read", null));
92
+ const entry = { at, ttl: FRESH_MS, promise };
93
+ held = entry;
94
+ void promise.then((payload) => { if (!payload) entry.ttl = RETRY_MS; });
95
+ return promise;
96
+ };
97
+ }
98
+
99
+ /** The record from Gloom Cloud, shared by every caller in the app. */
100
+ export const loadFxInterventions = createFxInterventionsLoader(apiClient);
101
+
102
+ /** The pair a listing is, when one side is the yen: USD and JPY for USDJPY=X or JPY=X. */
103
+ export function fxInterventionPair(symbol: string, exchange?: string): FxInterventionPair | null {
104
+ const spelling = currencyPairSpelling(symbol, exchange);
105
+ if (!spelling || spelling.ambiguous) return null;
106
+ const base = spelling.symbol.slice(0, 3), quote = spelling.symbol.slice(3, 6);
107
+ return base === "JPY" || quote === "JPY" ? { base, quote } : null;
108
+ }
109
+
110
+ const inPair = (run: Pick<FxInterventionRun, "sold" | "bought">, pair: FxInterventionPair) => (
111
+ run.sold === pair.base && run.bought === pair.quote || run.sold === pair.quote && run.bought === pair.base
112
+ );
113
+ /** USD/JPY either way round: the only pair a monthly total, which names none, is shown for. */
114
+ const isDollarYen = (pair: FxInterventionPair) => inPair({ sold: "USD", bought: "JPY" }, pair);
115
+
116
+ /** The pair's interventions, oldest first. */
117
+ function fxInterventionsIn(payload: FxInterventionsPayload, pair: FxInterventionPair): FxInterventionRun[] {
118
+ return payload.interventions.filter((run) => inPair(run, pair));
119
+ }
120
+
121
+ /** Which way the ministry went. */
122
+ function fxInterventionSide(run: Pick<FxInterventionRun, "sold" | "bought">): FxInterventionSide | null {
123
+ return run.bought === "JPY" ? "yen bought" : run.sold === "JPY" ? "yen sold" : null;
124
+ }
125
+
126
+ /**
127
+ * Monthly totals, or the part of one, no published day accounts for yet: for
128
+ * USD/JPY only, since a total names no pair and nearly every intervention
129
+ * since 2004 has been in it. A month that runs past the daily record counts
130
+ * from the day after it.
131
+ */
132
+ function undatedTotals(payload: FxInterventionsPayload, pair: FxInterventionPair): UndatedTotal[] {
133
+ if (!isDollarYen(pair)) return [];
134
+ return payload.months.filter((month) => month.undatedAmountJpy > 0).map((month) => {
135
+ const after = month.daysKnown === "partial" && payload.dailyThrough ? nextDay(payload.dailyThrough) : month.from;
136
+ return { from: after > month.from && after <= month.to ? after : month.from, to: month.to, amountJpy: month.undatedAmountJpy, releasedOn: month.releasedOn };
137
+ });
138
+ }
139
+
140
+ function dayText(date: string, withYear = true): string {
141
+ const [year, month, day] = date.split("-").map(Number);
142
+ return `${day} ${MONTHS[month! - 1]}${withYear ? ` ${year}` : ""}`;
143
+ }
144
+
145
+ /** 22 Sep 2022, 21–24 Oct 2022, 29 Apr–1 May 2024, 29 Dec 2003–16 Jan 2004. */
146
+ function spanText(from: string, to: string, withYear = true): string {
147
+ if (from === to) return dayText(from, withYear);
148
+ if (from.slice(0, 7) === to.slice(0, 7)) return `${Number(from.slice(8))}–${dayText(to, withYear)}`;
149
+ return `${dayText(from, withYear && from.slice(0, 4) !== to.slice(0, 4))}–${dayText(to, withYear)}`;
150
+ }
151
+
152
+ /** ¥11,734.9 billion: the ministry's own unit and precision. */
153
+ function yenText(amountJpy: number): string {
154
+ return `¥${(amountJpy / 1e9).toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 })} billion`;
155
+ }
156
+
157
+ /** ¥11.7tn, ¥780bn: short enough for a list or a chart caption. */
158
+ function yenShort(amountJpy: number): string {
159
+ return amountJpy >= 1e12 ? `¥${(amountJpy / 1e12).toFixed(1)}tn` : `¥${Math.round(amountJpy / 1e9).toLocaleString("en-US")}bn`;
160
+ }
161
+
162
+ /** Dollars sold for yen; the ministry's words when a side has no code. */
163
+ function directionText(run: Pick<FxInterventionRun, "sold" | "bought" | "pair">): string {
164
+ const sold = run.sold && CURRENCY_WORDS[run.sold], bought = run.bought && CURRENCY_WORDS[run.bought];
165
+ return sold && bought ? `${sold} sold for ${bought}` : run.pair;
166
+ }
167
+
168
+ const pairText = (pair: FxInterventionPair) => `${pair.base}/${pair.quote}`;
169
+ const runText = (run: FxInterventionRun) => (
170
+ `${spanText(run.from, run.to)}, ${yenText(run.amountJpy)} of ${directionText(run)}${run.days > 1 ? ` on ${run.days} days` : ""}`
171
+ );
172
+ const periodText = (total: UndatedTotal) => `from ${dayText(total.from, total.from.slice(0, 4) !== total.to.slice(0, 4))} to ${dayText(total.to)}`;
173
+ const releasedText = (total: UndatedTotal) => `a monthly total released ${dayText(total.releasedOn)}: its days and pair come with the quarterly release`;
174
+ /** The last day any release covers, a monthly one included. */
175
+ function recordsThrough(payload: FxInterventionsPayload): string | null {
176
+ return [payload.dailyThrough, ...payload.months.map((month) => month.to)].filter((date): date is string => !!date).sort().at(-1) ?? null;
177
+ }
178
+
179
+ /**
180
+ * `fx`'s note for a yen pair: the ministry's latest intervention in it, and
181
+ * for USD/JPY any monthly total its days have not been published for yet.
182
+ * Nothing for a pair it never intervened in and no undated total.
183
+ */
184
+ export function fxInterventionLatestNote(payload: FxInterventionsPayload, pair: FxInterventionPair): string | null {
185
+ const last = fxInterventionsIn(payload, pair).at(-1);
186
+ const undated = undatedTotals(payload, pair).at(-1);
187
+ if (!last && !undated) return null;
188
+ const through = recordsThrough(payload);
189
+ const sentences = [
190
+ ...undated ? [`Japan's Ministry of Finance reported ${yenText(undated.amountJpy)} of intervention ${periodText(undated)}, ${releasedText(undated)}.`] : [],
191
+ ...last ? [`${undated ? "Its last dated intervention" : "Japan's Ministry of Finance last intervened"} in ${pairText(pair)}: ${runText(last)}.`] : [],
192
+ ];
193
+ return `${sentences.join(" ")}${through ? ` Records through ${dayText(through)}.` : ""}`;
194
+ }
195
+
196
+ /** At most this many interventions are named in a window; older ones are counted. */
197
+ const NAMED_INTERVENTIONS = 6;
198
+
199
+ /**
200
+ * `history`'s note: the ministry's interventions in the pair between the
201
+ * first bar shown and the end of the last one's period, newest last, in short
202
+ * amounts, and for USD/JPY a monthly total in it whose days are not published
203
+ * yet. Nothing when the bars span none.
204
+ */
205
+ export function fxInterventionWindowNote(payload: FxInterventionsPayload, pair: FxInterventionPair, from: string, to: string): string | null {
206
+ const runs = fxInterventionsIn(payload, pair).filter((run) => run.to >= from && run.from <= to);
207
+ const undated = undatedTotals(payload, pair).filter((total) => total.to >= from && total.from <= to);
208
+ if (runs.length === 0 && undated.length === 0) return null;
209
+ const named = runs.slice(-NAMED_INTERVENTIONS);
210
+ const earlier = runs.length - named.length;
211
+ const sides = new Set(runs.map(fxInterventionSide));
212
+ const side = sides.size === 1 ? [...sides][0] : null;
213
+ const lead = side === "yen bought" ? "bought yen" : side === "yen sold" ? "sold yen" : "intervened";
214
+ const entry = (run: FxInterventionRun) => {
215
+ const own = side ? null : fxInterventionSide(run);
216
+ return `${spanText(run.from, run.to)} ${yenShort(run.amountJpy)}${own ? ` ${own}` : ""}`;
217
+ };
218
+ const sentences = [
219
+ ...named.length > 0 ? [`Japan's Ministry of Finance ${lead} in ${pairText(pair)} in these bars: ${named.map(entry).join("; ")}${
220
+ earlier > 0 ? `; and ${earlier} earlier from ${dayText(runs[0]!.from)}` : ""}.`] : [],
221
+ ...undated.map((total) => `${named.length > 0 ? "It also" : "Japan's Ministry of Finance"} reported ${yenShort(total.amountJpy)} ${periodText(total)}, ${releasedText(total)}.`),
222
+ ];
223
+ return sentences.join(" ");
224
+ }
225
+
226
+ /** A chart marker for one intervention, or for a total its days are not published for yet. */
227
+ export interface FxInterventionMarker {
228
+ id: string;
229
+ date: string;
230
+ /** A total's last day: it is drawn from its first day to here. */
231
+ endDate?: string;
232
+ /** Its caption, longest first: the `MoF` prefix goes first when room is short, never the dates. */
233
+ captions: string[];
234
+ /** A total with no day yet: drawn dotted across its period. */
235
+ undated: boolean;
236
+ amountJpy: number;
237
+ side: FxInterventionSide | null;
238
+ }
239
+
240
+ const PAIR_NOT_PUBLISHED = "pair not yet published";
241
+
242
+ /** The pair's interventions, then for USD/JPY any total without days, as chart markers. */
243
+ export function fxInterventionMarkers(payload: FxInterventionsPayload, pair: FxInterventionPair): FxInterventionMarker[] {
244
+ return [
245
+ ...fxInterventionsIn(payload, pair).map((run): FxInterventionMarker => {
246
+ const amount = yenShort(run.amountJpy), side = fxInterventionSide(run);
247
+ const told = side ? `${amount} ${side}` : amount;
248
+ return {
249
+ id: `mof:${run.from}:${run.sold}:${run.bought}`, date: run.from, captions: [...new Set([`MoF ${told}`, told, amount])],
250
+ undated: false, amountJpy: run.amountJpy, side,
251
+ };
252
+ }),
253
+ ...undatedTotals(payload, pair).map((total): FxInterventionMarker => {
254
+ const dated = `${yenShort(total.amountJpy)} ${spanText(total.from, total.to, false)}`;
255
+ return {
256
+ id: `mof:${total.from}:${total.to}`, date: total.from, endDate: total.to,
257
+ captions: [`MoF ${dated}, ${PAIR_NOT_PUBLISHED}`, `${dated}, ${PAIR_NOT_PUBLISHED}`, dated],
258
+ undated: true, amountJpy: total.amountJpy, side: null,
259
+ };
260
+ }),
261
+ ];
262
+ }
263
+
264
+ /** One caption for markers too close to caption apart: their sum and count, and the side when they share one. */
265
+ export function fxInterventionSharedCaptions(markers: readonly FxInterventionMarker[]): string[] {
266
+ const total = `${yenShort(markers.reduce((sum, marker) => sum + marker.amountJpy, 0))} ×${markers.length}`;
267
+ const sides = new Set(markers.map((marker) => marker.side));
268
+ const side = sides.size === 1 ? [...sides][0] : null;
269
+ return side ? [`MoF ${total} ${side}`, `${total} ${side}`, total] : [`MoF ${total}`, total];
270
+ }