@gloom-sh/terminal 0.20.17 → 0.20.18

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 (304) hide show
  1. package/package.json +3 -1
  2. package/src/account/auth-dialog.tsx +19 -1
  3. package/src/account/billing.ts +2 -1
  4. package/src/account/heard-from-question.tsx +235 -0
  5. package/src/account/heard-from.ts +97 -0
  6. package/src/api-client/data.ts +3 -2
  7. package/src/api-client/heard-from.ts +72 -0
  8. package/src/api-client/index.ts +63 -6
  9. package/src/api-client/mna.ts +18 -0
  10. package/src/api-client/supply-chain.ts +9 -0
  11. package/src/api-client/types/billing.ts +35 -1
  12. package/src/app/global-shortcuts.ts +5 -3
  13. package/src/app/pro-welcome/keys.ts +27 -0
  14. package/src/app/pro-welcome/model.ts +158 -0
  15. package/src/app/pro-welcome/row.tsx +176 -0
  16. package/src/app/pro-welcome/use-pro-welcome.ts +156 -0
  17. package/src/app/runtime/external-profile-changes.ts +135 -0
  18. package/src/app.tsx +33 -2
  19. package/src/architecture/core-builtin-allowlist.json +1 -1
  20. package/src/architecture/floating-promise-allowlist.json +0 -1
  21. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  22. package/src/cli/alert-listing.ts +98 -0
  23. package/src/cli/commands/market.ts +138 -22
  24. package/src/cli/commands/overview.ts +7 -1
  25. package/src/cli/commands/plugins.ts +3 -2
  26. package/src/cli/commands/search.ts +30 -6
  27. package/src/cli/context.ts +16 -5
  28. package/src/cli/csv-export.ts +2 -1
  29. package/src/cli/desktop-pane-shot.ts +72 -9
  30. package/src/cli/glossary.ts +64 -10
  31. package/src/cli/history-demergers.ts +117 -0
  32. package/src/cli/history-rows.ts +6 -2
  33. package/src/cli/index.ts +1 -0
  34. package/src/cli/known-gaps.ts +16 -0
  35. package/src/cli/known-us-stocks.ts +18 -0
  36. package/src/cli/listing-arg.ts +105 -15
  37. package/src/cli/pane-functions/catalog-snapshot-build.ts +83 -0
  38. package/src/cli/pane-functions/catalog-snapshot.json +866 -0
  39. package/src/cli/pane-functions/catalog-snapshot.ts +62 -0
  40. package/src/cli/pane-functions/catalog.ts +50 -16
  41. package/src/cli/pane-functions/data.ts +16 -4
  42. package/src/cli/pane-functions/dom.ts +24 -6
  43. package/src/cli/pane-functions/freshness.ts +17 -1
  44. package/src/cli/pane-functions/index.ts +100 -42
  45. package/src/cli/pane-functions/resolver.ts +8 -5
  46. package/src/cli/pane-functions/screenshot-assessment.ts +30 -7
  47. package/src/cli/pane-functions/screenshot-payload.ts +21 -0
  48. package/src/cli/pane-functions/screenshot-render.ts +3 -1
  49. package/src/cli/quote-answer.ts +32 -16
  50. package/src/cli/registry.ts +22 -2
  51. package/src/cli/result.ts +5 -4
  52. package/src/cli/series-search.ts +45 -6
  53. package/src/cli/shot-temp-dir.ts +4 -9
  54. package/src/components/chart/composite/legend.tsx +43 -18
  55. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +3 -3
  56. package/src/components/chart/composite/price-axis-labels.tsx +7 -5
  57. package/src/components/chart-table/header.tsx +9 -0
  58. package/src/components/chart-table/layout.ts +11 -11
  59. package/src/components/command-bar/pane-templates/items.ts +17 -1
  60. package/src/components/command-bar/routes/root/provider-search.ts +10 -1
  61. package/src/components/command-bar/routes/root/results.ts +34 -2
  62. package/src/components/command-bar/routes/root/runtime.ts +8 -1
  63. package/src/components/command-bar/routes/ticker-search/route.ts +5 -0
  64. package/src/components/command-bar/workflow/alert.ts +19 -8
  65. package/src/components/data-table/view.tsx +15 -2
  66. package/src/components/form-modal/content.tsx +9 -4
  67. package/src/components/index.ts +1 -1
  68. package/src/components/layout/header.tsx +9 -5
  69. package/src/components/layout/pane/capture-status.ts +6 -0
  70. package/src/components/layout/pane/footer/index.tsx +2 -0
  71. package/src/components/layout/pane/footer/model.ts +113 -15
  72. package/src/components/layout/pane/header.tsx +16 -2
  73. package/src/components/market-board/index.tsx +4 -2
  74. package/src/components/onboarding/onboarding-frame.tsx +6 -2
  75. package/src/components/onboarding/onboarding-keyboard.ts +7 -1
  76. package/src/components/onboarding/onboarding-wizard.tsx +3 -1
  77. package/src/components/onboarding/portfolio-step/positions-panel.tsx +24 -15
  78. package/src/components/onboarding/setup-cards.ts +36 -0
  79. package/src/components/onboarding/use-onboarding-progress.ts +22 -1
  80. package/src/components/onboarding/wizard-account.ts +6 -1
  81. package/src/components/onboarding/wizard-model.ts +32 -6
  82. package/src/components/onboarding/wizard-positions.ts +1 -1
  83. package/src/components/sign-in-gate.tsx +3 -1
  84. package/src/components/toggle-list.tsx +6 -8
  85. package/src/components/ui/confirm-dialog.tsx +47 -7
  86. package/src/components/ui/data-table/types.ts +8 -0
  87. package/src/components/ui/display.tsx +17 -2
  88. package/src/components/ui/index.ts +1 -1
  89. package/src/components/ui/stat-grid.tsx +4 -0
  90. package/src/components/ui/status.tsx +13 -1
  91. package/src/components/ui/table-layout.ts +2 -1
  92. package/src/components/use-pane-notice-footer.tsx +16 -3
  93. package/src/data/config/store/index.ts +31 -0
  94. package/src/data/config/store/node.ts +61 -11
  95. package/src/data/config/store/normalize.ts +4 -6
  96. package/src/data/config/store/shared-file.ts +309 -0
  97. package/src/data/profile-merge.ts +299 -0
  98. package/src/data/sqlite/checkpointer.ts +11 -1
  99. package/src/data/sqlite/database.ts +1 -1
  100. package/src/data/ticker-repository.ts +134 -10
  101. package/src/data/ticker-store.ts +67 -0
  102. package/src/data/ticker-writes.ts +5 -0
  103. package/src/i18n/es.ts +27 -0
  104. package/src/i18n/ja.ts +27 -0
  105. package/src/i18n/ko.ts +27 -0
  106. package/src/i18n/zh-cn.ts +27 -0
  107. package/src/i18n/zh-tw.ts +27 -0
  108. package/src/layout-marketplace/gallery-desktop.tsx +2 -2
  109. package/src/market-data/ah-pair.ts +103 -0
  110. package/src/market-data/depositary-pair.ts +6 -2
  111. package/src/market-data/hooks.tsx +33 -2
  112. package/src/market-data/market/change-basis.ts +2 -1
  113. package/src/market-data/market/header-market.ts +11 -0
  114. package/src/market-data/split-terms.ts +28 -0
  115. package/src/plugins/builtin/account-management/footer.ts +1 -1
  116. package/src/plugins/builtin/account-management/keyboard.ts +4 -0
  117. package/src/plugins/builtin/account-management/model.ts +1 -0
  118. package/src/plugins/builtin/account-management/pane.tsx +75 -7
  119. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +12 -5
  120. package/src/plugins/builtin/account-management/pro-cancel.tsx +197 -0
  121. package/src/plugins/builtin/account-management/trial-cancel.ts +1 -1
  122. package/src/plugins/builtin/alerts/cli-move.ts +2 -2
  123. package/src/plugins/builtin/alerts/cli.ts +36 -30
  124. package/src/plugins/builtin/alerts/constants.ts +10 -0
  125. package/src/plugins/builtin/alerts/earnings-listing.ts +20 -0
  126. package/src/plugins/builtin/alerts/format.ts +24 -8
  127. package/src/plugins/builtin/alerts/index.tsx +38 -9
  128. package/src/plugins/builtin/alerts/move-checks.ts +7 -0
  129. package/src/plugins/builtin/alerts/pane.tsx +1 -1
  130. package/src/plugins/builtin/alerts/quotes.ts +26 -2
  131. package/src/plugins/builtin/alerts/scheduled.ts +6 -1
  132. package/src/plugins/builtin/alerts/types.ts +7 -0
  133. package/src/plugins/builtin/analytics/manual-value.ts +61 -0
  134. package/src/plugins/builtin/analytics/risk-book.ts +7 -7
  135. package/src/plugins/builtin/analytics/risk-client.ts +26 -13
  136. package/src/plugins/builtin/analytics/risk-headless.ts +13 -8
  137. package/src/plugins/builtin/analytics/risk-model.ts +92 -4
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +85 -38
  139. package/src/plugins/builtin/awards/pane.tsx +1 -1
  140. package/src/plugins/builtin/broker-trading/orders.tsx +2 -2
  141. package/src/plugins/builtin/central-bank-rates/model.ts +8 -2
  142. package/src/plugins/builtin/central-bank-rates/pane.tsx +5 -3
  143. package/src/plugins/builtin/chart-composer/cli-options.ts +4 -2
  144. package/src/plugins/builtin/chart-composer/data-catalog-pane.tsx +2 -6
  145. package/src/plugins/builtin/chart-composer/pane.tsx +5 -2
  146. package/src/plugins/builtin/cloud/auth-actions.tsx +11 -6
  147. package/src/plugins/builtin/cloud/company-picker.tsx +5 -3
  148. package/src/plugins/builtin/cloud/upgrade-command.ts +1 -1
  149. package/src/plugins/builtin/company-kpis/headless.ts +9 -4
  150. package/src/plugins/builtin/company-kpis/latest.ts +45 -0
  151. package/src/plugins/builtin/company-kpis/model.ts +38 -8
  152. package/src/plugins/builtin/company-kpis/pane.tsx +22 -8
  153. package/src/plugins/builtin/composite/alt-data.ts +20 -0
  154. package/src/plugins/builtin/composite/application.ts +14 -0
  155. package/src/plugins/builtin/composite/broker.ts +12 -0
  156. package/src/plugins/builtin/composite/credit.ts +33 -0
  157. package/src/plugins/builtin/composite/crypto.ts +10 -0
  158. package/src/plugins/builtin/composite/earnings.ts +12 -0
  159. package/src/plugins/builtin/composite/filings.ts +13 -0
  160. package/src/plugins/builtin/composite/futures-commodities.ts +23 -0
  161. package/src/plugins/builtin/composite/global-markets.ts +12 -0
  162. package/src/plugins/builtin/composite/options-volatility.ts +23 -0
  163. package/src/plugins/builtin/composite/ownership.ts +23 -0
  164. package/src/plugins/builtin/composite/portfolio.ts +10 -0
  165. package/src/plugins/builtin/composite/quant.ts +15 -0
  166. package/src/plugins/builtin/composite/rates-macro.ts +30 -0
  167. package/src/plugins/builtin/composite/screeners.ts +11 -0
  168. package/src/plugins/builtin/composite/shared.ts +11 -0
  169. package/src/plugins/builtin/composite/ticker-core.ts +36 -0
  170. package/src/plugins/builtin/congress-trades/headless.ts +31 -3
  171. package/src/plugins/builtin/correlation/index.tsx +13 -17
  172. package/src/plugins/builtin/correlation/matrix/model.ts +18 -0
  173. package/src/plugins/builtin/dividend-yield/client.ts +57 -16
  174. package/src/plugins/builtin/dividend-yield/headless.ts +17 -11
  175. package/src/plugins/builtin/dividend-yield/model.ts +4 -3
  176. package/src/plugins/builtin/dividend-yield/pane.tsx +22 -18
  177. package/src/plugins/builtin/dividend-yield/ranking.ts +1 -1
  178. package/src/plugins/builtin/dividend-yield/types.ts +4 -0
  179. package/src/plugins/builtin/dividend-yield/view.ts +23 -12
  180. package/src/plugins/builtin/earnings/fiscal-quarter.ts +39 -0
  181. package/src/plugins/builtin/earnings/headless.ts +7 -4
  182. package/src/plugins/builtin/earnings/history-model.ts +6 -4
  183. package/src/plugins/builtin/earnings/history-table.ts +4 -3
  184. package/src/plugins/builtin/earnings-calls/pane.tsx +8 -2
  185. package/src/plugins/builtin/econ/calendar-model.ts +16 -0
  186. package/src/plugins/builtin/econ/index.tsx +3 -0
  187. package/src/plugins/builtin/equity-screener/headless.ts +4 -1
  188. package/src/plugins/builtin/equity-screener/model.ts +7 -6
  189. package/src/plugins/builtin/estimate-revisions/headless.ts +1 -1
  190. package/src/plugins/builtin/exposure/model.ts +10 -0
  191. package/src/plugins/builtin/exposure/pane.tsx +10 -3
  192. package/src/plugins/builtin/fx-matrix/amount.ts +15 -1
  193. package/src/plugins/builtin/fx-matrix/headless.ts +12 -6
  194. package/src/plugins/builtin/fx-matrix/index.tsx +23 -5
  195. package/src/plugins/builtin/fx-matrix/settings.ts +9 -4
  196. package/src/plugins/builtin/kelly-sizer/pane.tsx +9 -4
  197. package/src/plugins/builtin/market-valuation/pane.tsx +22 -10
  198. package/src/plugins/builtin/mna/detail.tsx +67 -6
  199. package/src/plugins/builtin/mna/headless.ts +128 -13
  200. package/src/plugins/builtin/mna/model.ts +219 -16
  201. package/src/plugins/builtin/mna/pane.tsx +34 -6
  202. package/src/plugins/builtin/money-markets/model.ts +14 -5
  203. package/src/plugins/builtin/money-markets/pane.tsx +4 -3
  204. package/src/plugins/builtin/news/wire/news/footer.ts +3 -8
  205. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +22 -6
  206. package/src/plugins/builtin/options-scenario/csp-screen.ts +39 -12
  207. package/src/plugins/builtin/options-scenario/strategy-screen.ts +7 -5
  208. package/src/plugins/builtin/pe-band/client.ts +13 -1
  209. package/src/plugins/builtin/pe-band/headless.ts +2 -2
  210. package/src/plugins/builtin/pe-band/model.ts +63 -10
  211. package/src/plugins/builtin/pe-band/pane.tsx +5 -5
  212. package/src/plugins/builtin/portfolio-list/allocation-rows.ts +26 -7
  213. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +66 -13
  214. package/src/plugins/builtin/portfolio-list/cli/render.ts +76 -33
  215. package/src/plugins/builtin/portfolio-list/headless.ts +69 -22
  216. package/src/plugins/builtin/portfolio-list/pane/data.ts +3 -3
  217. package/src/plugins/builtin/portfolio-list/pane/index.tsx +29 -14
  218. package/src/plugins/builtin/portfolio-list/summary/index.tsx +2 -2
  219. package/src/plugins/builtin/relative-rotation/pane.tsx +2 -3
  220. package/src/plugins/builtin/research/corporate-actions-pane.tsx +5 -1
  221. package/src/plugins/builtin/research/event-model.ts +31 -13
  222. package/src/plugins/builtin/research/headless.ts +8 -1
  223. package/src/plugins/builtin/research/relative-valuation-pane.tsx +19 -17
  224. package/src/plugins/builtin/sectors/index.tsx +6 -9
  225. package/src/plugins/builtin/shared/cloud-upgrade.ts +1 -1
  226. package/src/plugins/builtin/shared/earnings-report.ts +19 -4
  227. package/src/plugins/builtin/shared/report-freshness.ts +2 -3
  228. package/src/plugins/builtin/supply-chain/client.ts +34 -9
  229. package/src/plugins/builtin/supply-chain/evidence.ts +3 -2
  230. package/src/plugins/builtin/supply-chain/flow.tsx +4 -3
  231. package/src/plugins/builtin/supply-chain/graph-model.ts +14 -7
  232. package/src/plugins/builtin/supply-chain/graph-pane.tsx +3 -1
  233. package/src/plugins/builtin/supply-chain/graph.tsx +6 -3
  234. package/src/plugins/builtin/supply-chain/headless.ts +19 -4
  235. package/src/plugins/builtin/supply-chain/model.ts +50 -6
  236. package/src/plugins/builtin/supply-chain/pane.tsx +76 -16
  237. package/src/plugins/builtin/ticker-detail/adr-pair/ah.ts +62 -0
  238. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +119 -20
  239. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +51 -1
  240. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +25 -14
  241. package/src/plugins/builtin/ticker-detail/overview/model.ts +17 -1
  242. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  243. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +9 -2
  244. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +9 -2
  245. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +5 -2
  246. package/src/plugins/builtin/volatility/model.ts +17 -0
  247. package/src/plugins/builtin/volatility/pane.tsx +13 -4
  248. package/src/plugins/builtin/world-indices/index.tsx +2 -0
  249. package/src/plugins/builtin/world-indices/table.tsx +15 -0
  250. package/src/plugins/builtin/world-venue-map/evidence.ts +3 -2
  251. package/src/plugins/builtin/world-venue-map/headless.ts +28 -16
  252. package/src/plugins/builtin/world-venue-map/index.ts +19 -6
  253. package/src/plugins/builtin/world-venue-map/layered-pane.tsx +9 -5
  254. package/src/plugins/builtin/world-venue-map/layers.ts +33 -11
  255. package/src/plugins/builtin/world-venue-map/map.tsx +12 -0
  256. package/src/plugins/builtin/world-venue-map/pane.tsx +35 -6
  257. package/src/plugins/builtin/world-venue-map/place.ts +119 -0
  258. package/src/plugins/catalog-data.ts +20 -0
  259. package/src/plugins/catalog-lazy.ts +51 -0
  260. package/src/plugins/catalog-ui.ts +16 -18
  261. package/src/plugins/host-smoke.ts +5 -2
  262. package/src/portfolio/allocation.ts +79 -19
  263. package/src/portfolio/cash-balances.ts +76 -0
  264. package/src/portfolio/mutations.ts +43 -8
  265. package/src/public/__snapshots__/public-api.test.ts.snap +1 -0
  266. package/src/renderers/desktop/window-layouts.ts +14 -0
  267. package/src/renderers/dom/data-table/row.tsx +2 -0
  268. package/src/renderers/dom/host/tabs.tsx +57 -8
  269. package/src/renderers/dom/styles.css +13 -5
  270. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +4 -0
  271. package/src/renderers/electrobun/bun/desktop/backend.ts +22 -1
  272. package/src/renderers/electrobun/bun/window/native-min-size.ts +6 -1
  273. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  274. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +50 -12
  275. package/src/renderers/electrobun/view/remote/ticker-repository.ts +10 -0
  276. package/src/series/standalone-catalog.ts +5 -4
  277. package/src/series/standalone.ts +13 -7
  278. package/src/sources/gloomberb-cloud/index.ts +14 -3
  279. package/src/sources/gloomberb-cloud/perpetuals.ts +60 -3
  280. package/src/sources/provider-router/financials.ts +20 -13
  281. package/src/sources/provider-router/index.ts +4 -0
  282. package/src/sources/provider-router/search.ts +1 -0
  283. package/src/sync/collections-contributor.ts +3 -1
  284. package/src/sync/config-merge.ts +10 -1
  285. package/src/sync/sanitize.ts +26 -2
  286. package/src/tickers/company-name-listing.ts +16 -2
  287. package/src/tickers/listing-fate.ts +12 -8
  288. package/src/tickers/renamed-listings.ts +43 -10
  289. package/src/tickers/search/home-listing.ts +28 -0
  290. package/src/tickers/search/index.ts +19 -7
  291. package/src/tickers/terminal-codes.ts +11 -1
  292. package/src/time-series/resolve.ts +3 -1
  293. package/src/time-series/spec.ts +2 -2
  294. package/src/time-series/types.ts +1 -1
  295. package/src/types/data-provider.ts +11 -0
  296. package/src/types/financials.ts +39 -3
  297. package/src/types/ticker.ts +10 -2
  298. package/src/utils/cli-output.ts +1 -1
  299. package/src/utils/declared-dividends.ts +13 -1
  300. package/src/utils/dividend-cash.ts +5 -1
  301. package/src/utils/forward-dividend.ts +4 -3
  302. package/src/utils/remove-folder.ts +37 -0
  303. package/src/utils/trailing-dividend.ts +1 -1
  304. package/src/plugins/builtin/composite-plugins.ts +0 -285
@@ -0,0 +1,309 @@
1
+ import { constants, watch, type FSWatcher } from "fs";
2
+ import { open, readFile, rm, stat } from "fs/promises";
3
+ import { basename, dirname } from "path";
4
+ import { applyProfileEdits, diffProfile, type ProfileEdit, type ProfileJson } from "../../profile-merge";
5
+ import { debugLog } from "../../../utils/debug-log";
6
+
7
+ /**
8
+ * config.json is shared: the app keeps it in memory and saves it as it goes,
9
+ * while a `gloom` command run beside it (`alerts add`, `config set`,
10
+ * `watchlist create`) reads, changes and writes it too. Each program that
11
+ * writes the file goes through here, so neither undoes the other:
12
+ *
13
+ * - what this program last read from the file or wrote to it is kept, and a
14
+ * file that no longer reads so was changed by another program;
15
+ * - that change is folded into whatever this program writes next, and handed
16
+ * to the program's listeners (the app folds it into its state);
17
+ * - a write happens under a lock file, so two programs never read the same
18
+ * file and then each write over the other's change.
19
+ *
20
+ * A config object records how many of those changes it already holds (on a
21
+ * symbol, which spreads copy and JSON leaves out). One built before the app
22
+ * took a change in, a save still waiting on its timer, is written with that
23
+ * change folded in, while one built after it is written as it is, so an edit
24
+ * made in the app after taking the change in is never undone by it again.
25
+ */
26
+
27
+ const log = debugLog.createLogger("config");
28
+
29
+ const CHANGES_HELD = Symbol.for("gloomberb.config.externalChangesHeld");
30
+
31
+ /** A lock older than this was left by a program that stopped mid-write. */
32
+ const LOCK_STALE_MS = 10_000;
33
+ /** A lock held longer than this is waited out no longer: the write goes ahead. */
34
+ const LOCK_WAIT_MS = 2_000;
35
+ const LOCK_RETRY_MS = 15;
36
+ /** How soon a change event is read, so one write's several events read once. */
37
+ const CHECK_DELAY_MS = 50;
38
+ /** How often the file is looked at besides its change events, which some disks never send. */
39
+ const POLL_MS = 3_000;
40
+
41
+ export interface SharedFileChange {
42
+ /** The change's place among the ones found: a config holding it has a count past this. */
43
+ readonly index: number;
44
+ readonly edits: readonly ProfileEdit[];
45
+ }
46
+
47
+ interface SharedFileState {
48
+ /** The file as this program last read or wrote it; null before either. */
49
+ known: string | null;
50
+ /** The changes other programs made, in the order they were found. */
51
+ readonly changes: SharedFileChange[];
52
+ readonly listeners: Set<(change: SharedFileChange) => void>;
53
+ /** The save in flight or queued last; it never rejects. */
54
+ queue: Promise<void>;
55
+ stopWatching: (() => void) | null;
56
+ }
57
+
58
+ const states = new Map<string, SharedFileState>();
59
+
60
+ function stateFor(path: string): SharedFileState {
61
+ let state = states.get(path);
62
+ if (!state) {
63
+ state = { known: null, changes: [], listeners: new Set(), queue: Promise.resolve(), stopWatching: null };
64
+ states.set(path, state);
65
+ }
66
+ return state;
67
+ }
68
+
69
+ /**
70
+ * How many of the file's changes `value` holds: those found before it was
71
+ * read or took them in. A value that does not say (built from scratch, or
72
+ * passed through a structured clone) counts as holding `unmarked`, every
73
+ * change found so far unless the caller knows better.
74
+ */
75
+ export function changesHeld(path: string, value: object, unmarked = stateFor(path).changes.length): number {
76
+ const held = (value as Record<symbol, unknown>)[CHANGES_HELD];
77
+ return typeof held === "number" ? held : unmarked;
78
+ }
79
+
80
+ /** Marks `value` as holding every change found so far, or the first `count`. */
81
+ export function markChangesHeld<T extends object>(path: string, value: T, count = stateFor(path).changes.length): T {
82
+ (value as Record<symbol, unknown>)[CHANGES_HELD] = count;
83
+ return value;
84
+ }
85
+
86
+ /** The file was read: its first read is what later reads and writes are compared with. */
87
+ export function noteSharedFileRead(path: string, contents: string): void {
88
+ const state = stateFor(path);
89
+ if (state.known === null) state.known = contents;
90
+ }
91
+
92
+ /** The file is gone (a reset): the next write starts over. */
93
+ export function forgetSharedFile(path: string): void {
94
+ stateFor(path).known = null;
95
+ }
96
+
97
+ /** The changes found after the first `held`, to fold into a copy built before them. */
98
+ export function changesSince(path: string, held: number): SharedFileChange[] {
99
+ return stateFor(path).changes.slice(held);
100
+ }
101
+
102
+ function parse(contents: string): ProfileJson | undefined {
103
+ try {
104
+ return JSON.parse(contents) as ProfileJson;
105
+ } catch {
106
+ // Intentional ignore: a file that does not parse has nothing to merge; it is written over as before.
107
+ return undefined;
108
+ }
109
+ }
110
+
111
+ async function readIfPresent(path: string): Promise<string | null> {
112
+ try {
113
+ return await readFile(path, "utf-8");
114
+ } catch (error) {
115
+ if ((error as { code?: unknown } | null)?.code === "ENOENT") return null;
116
+ throw error;
117
+ }
118
+ }
119
+
120
+ /** Compares the file with what this program knows of it, and records what another program changed. */
121
+ function noteContents(path: string, state: SharedFileState, contents: string | null): void {
122
+ if (contents === null || contents === state.known) return;
123
+ const known = state.known;
124
+ state.known = contents;
125
+ if (known === null) return;
126
+ const before = parse(known);
127
+ const after = parse(contents);
128
+ if (before === undefined || after === undefined) return;
129
+ const edits = diffProfile(before, after);
130
+ if (edits.length === 0) return;
131
+ const change: SharedFileChange = { index: state.changes.length, edits };
132
+ state.changes.push(change);
133
+ log.info("config.changed.elsewhere", { edits: edits.length });
134
+ for (const listener of state.listeners) {
135
+ try {
136
+ listener(change);
137
+ } catch (error) {
138
+ log.warn("config.change.listener.failed", { error: error instanceof Error ? error.message : String(error) });
139
+ }
140
+ }
141
+ }
142
+
143
+ function enqueue(state: SharedFileState, job: () => Promise<void>): Promise<void> {
144
+ const result = state.queue.then(job);
145
+ state.queue = result.catch(() => { /* Intentional ignore: the caller receives result; the chain only keeps later jobs running. */ });
146
+ return result;
147
+ }
148
+
149
+ /**
150
+ * Writes `contents` (this program's copy, holding the first `held` changes)
151
+ * with every change it lacks folded in, including one found just now. Writes
152
+ * to one file run one after another in call order.
153
+ */
154
+ export function writeSharedFile(
155
+ path: string,
156
+ contents: string,
157
+ held: number,
158
+ write: (contents: string) => Promise<void>,
159
+ ): Promise<void> {
160
+ const state = stateFor(path);
161
+ return enqueue(state, () => withFileLock(path, async () => {
162
+ noteContents(path, state, await readIfPresent(path));
163
+ const output = foldChanges(contents, state.changes.slice(held));
164
+ await write(output);
165
+ state.known = output;
166
+ }));
167
+ }
168
+
169
+ function foldChanges(contents: string, changes: readonly SharedFileChange[]): string {
170
+ if (changes.length === 0) return contents;
171
+ const mine = parse(contents);
172
+ if (mine === undefined) return contents;
173
+ let merged = mine;
174
+ for (const change of changes) merged = applyProfileEdits(merged, change.edits);
175
+ return merged === mine ? contents : JSON.stringify(merged, null, 2);
176
+ }
177
+
178
+ /** Reads the file now and hands any change another program made to the listeners. */
179
+ function checkSharedFile(path: string): Promise<void> {
180
+ const state = stateFor(path);
181
+ return enqueue(state, async () => {
182
+ noteContents(path, state, await readIfPresent(path));
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Calls `listener` with each change another program makes to the file,
188
+ * found by watching it, or at the latest when this program next writes it.
189
+ * A listener runs before anything else is written, and must fold the change
190
+ * into this program's copy before it returns.
191
+ */
192
+ export function watchSharedFile(path: string, listener: (change: SharedFileChange) => void): () => void {
193
+ const state = stateFor(path);
194
+ state.listeners.add(listener);
195
+ if (!state.stopWatching) state.stopWatching = startWatching(path);
196
+ return () => {
197
+ state.listeners.delete(listener);
198
+ if (state.listeners.size === 0 && state.stopWatching) {
199
+ state.stopWatching();
200
+ state.stopWatching = null;
201
+ }
202
+ };
203
+ }
204
+
205
+ function startWatching(path: string): () => void {
206
+ let timer: ReturnType<typeof setTimeout> | null = null;
207
+ let lastSeen: string | null = null;
208
+ const check = () => {
209
+ timer = null;
210
+ checkSharedFile(path).catch((error: unknown) => {
211
+ log.warn("config.check.failed", { error: error instanceof Error ? error.message : String(error) });
212
+ });
213
+ };
214
+ const soon = () => {
215
+ if (timer) return;
216
+ timer = setTimeout(check, CHECK_DELAY_MS);
217
+ timer.unref?.();
218
+ };
219
+ let watcher: FSWatcher | null = null;
220
+ try {
221
+ // The folder, not the file: a save replaces the file, and a watch on the old one would see nothing after.
222
+ // Some systems name only the temporary file a save renames into place (config.json.<n>.tmp).
223
+ const name = basename(path);
224
+ watcher = watch(dirname(path), { persistent: false }, (_event, filename) => {
225
+ const changed = filename?.toString();
226
+ if (!changed || changed === name || changed.startsWith(`${name}.`)) soon();
227
+ });
228
+ watcher.on("error", () => {
229
+ watcher?.close();
230
+ watcher = null;
231
+ });
232
+ } catch {
233
+ // Intentional ignore: without change events the poll below still finds a change.
234
+ watcher = null;
235
+ }
236
+ const poll = setInterval(() => {
237
+ void stat(path).then((info) => {
238
+ const seen = `${info.mtimeMs}:${info.size}`;
239
+ if (lastSeen !== null && seen !== lastSeen) soon();
240
+ lastSeen = seen;
241
+ }, () => { /* Intentional ignore: a missing file is checked again on the next tick. */ });
242
+ }, POLL_MS);
243
+ poll.unref?.();
244
+ return () => {
245
+ if (timer) clearTimeout(timer);
246
+ clearInterval(poll);
247
+ watcher?.close();
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Runs `task` holding `<path>.lock`, which every program writing the file
253
+ * takes, so none reads the file while another is between its own read and
254
+ * write. A lock left by a program that stopped is taken over once stale, and
255
+ * one held too long is not waited on: a save never hangs on a lock.
256
+ */
257
+ async function withFileLock<T>(path: string, task: () => Promise<T>): Promise<T> {
258
+ const lockPath = `${path}.lock`;
259
+ const token = `${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
260
+ const deadline = Date.now() + LOCK_WAIT_MS;
261
+ let held = false;
262
+ for (;;) {
263
+ try {
264
+ const handle = await open(lockPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
265
+ try {
266
+ await handle.writeFile(token, "utf-8");
267
+ } finally {
268
+ await handle.close();
269
+ }
270
+ held = true;
271
+ break;
272
+ } catch (error) {
273
+ const code = (error as { code?: unknown } | null)?.code;
274
+ // No folder yet, or one that refuses the lock: the write goes ahead and reports its own failure.
275
+ if (code !== "EEXIST") break;
276
+ if (await lockIsStale(lockPath)) {
277
+ await rm(lockPath, { force: true }).catch(() => { /* Intentional ignore: another program may have taken it over first. */ });
278
+ continue;
279
+ }
280
+ if (Date.now() >= deadline) {
281
+ log.warn("config.lock.busy", { lockPath });
282
+ break;
283
+ }
284
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
285
+ }
286
+ }
287
+ try {
288
+ return await task();
289
+ } finally {
290
+ if (held) await releaseLock(lockPath, token);
291
+ }
292
+ }
293
+
294
+ async function lockIsStale(lockPath: string): Promise<boolean> {
295
+ try {
296
+ return Date.now() - (await stat(lockPath)).mtimeMs > LOCK_STALE_MS;
297
+ } catch {
298
+ // Intentional ignore: a lock gone meanwhile is free; the next try takes it.
299
+ return false;
300
+ }
301
+ }
302
+
303
+ async function releaseLock(lockPath: string, token: string): Promise<void> {
304
+ try {
305
+ if (await readFile(lockPath, "utf-8") === token) await rm(lockPath, { force: true });
306
+ } catch {
307
+ // Intentional ignore: a lock already gone, or taken over as stale, is not this write's to remove.
308
+ }
309
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Folds one writer's change to a saved profile document (config.json, a
3
+ * ticker row) into another copy of it, so two programs writing the same
4
+ * profile keep each other's edits: the app open in a terminal and a `gloom`
5
+ * command run beside it.
6
+ *
7
+ * `diffProfile` lists what changed between the copy a writer started from
8
+ * and the one it wrote; `applyProfileEdits` replays that list on any other
9
+ * copy. The edits are fine-grained, so unrelated changes never collide:
10
+ *
11
+ * - objects merge key by key;
12
+ * - lists of records with an `id` (or a pane's `instanceId`) merge record by
13
+ * record, keeping each side's additions, removals and order;
14
+ * - lists of plain values (symbols, ids) merge as sets;
15
+ * - a string that holds JSON (the alert lists) merges as the JSON it holds.
16
+ *
17
+ * When both sides changed the same value, the copy the edits land on keeps
18
+ * its own. A removal always lands: an alert or a watchlist one side deleted
19
+ * stays deleted, whatever the other changed in it meanwhile.
20
+ */
21
+
22
+ export type ProfileJson = null | boolean | number | string | ProfileJson[] | { [key: string]: ProfileJson };
23
+ type ProfileObject = { [key: string]: ProfileJson };
24
+
25
+ /** One step into a document: an object key, a record in a list by its id, or the JSON a string holds. */
26
+ type ProfileStep = { key: string } | { id: string } | { json: true };
27
+
28
+ export type ProfileEdit =
29
+ | { kind: "set"; path: ProfileStep[]; from: ProfileJson | undefined; to: ProfileJson }
30
+ | { kind: "remove"; path: ProfileStep[] }
31
+ | { kind: "members"; path: ProfileStep[]; from: ProfileJson[]; to: ProfileJson[]; add: ProfileJson[]; remove: ProfileJson[] }
32
+ | { kind: "insert"; path: ProfileStep[]; after: string | null; record: ProfileObject }
33
+ | { kind: "order"; path: ProfileStep[]; from: string[]; to: string[] };
34
+
35
+ const RECORD_KEYS = ["id", "instanceId"] as const;
36
+ type RecordKey = typeof RECORD_KEYS[number];
37
+
38
+ function isObject(value: unknown): value is ProfileObject {
39
+ return value !== null && typeof value === "object" && !Array.isArray(value);
40
+ }
41
+
42
+ export function sameProfileJson(a: unknown, b: unknown): boolean {
43
+ if (a === b) return true;
44
+ if (Array.isArray(a)) {
45
+ if (!Array.isArray(b) || a.length !== b.length) return false;
46
+ return a.every((entry, index) => sameProfileJson(entry, b[index]));
47
+ }
48
+ if (isObject(a)) {
49
+ if (!isObject(b)) return false;
50
+ const keys = Object.keys(a);
51
+ if (keys.length !== Object.keys(b).length) return false;
52
+ return keys.every((key) => Object.hasOwn(b, key) && sameProfileJson(a[key], b[key]));
53
+ }
54
+ return false;
55
+ }
56
+
57
+ /** The field that names each record of a list, when every entry is a record with a distinct one. */
58
+ function recordKeyOf(list: readonly ProfileJson[]): RecordKey | null {
59
+ if (list.length === 0) return null;
60
+ for (const key of RECORD_KEYS) {
61
+ const ids = new Set<string>();
62
+ if (list.every((entry) => isObject(entry) && typeof entry[key] === "string" && !ids.has(entry[key] as string) && ids.add(entry[key] as string))) {
63
+ return key;
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+
69
+ /** Both lists' record field: empty lists take the other's. */
70
+ function sharedRecordKey(a: readonly ProfileJson[], b: readonly ProfileJson[]): RecordKey | null {
71
+ const aKey = recordKeyOf(a);
72
+ const bKey = recordKeyOf(b);
73
+ if (a.length === 0) return bKey;
74
+ if (b.length === 0) return aKey;
75
+ return aKey === bKey ? aKey : null;
76
+ }
77
+
78
+ function recordId(entry: ProfileJson, key: RecordKey | null): string | null {
79
+ if (!isObject(entry)) return null;
80
+ if (key) return typeof entry[key] === "string" ? entry[key] as string : null;
81
+ for (const field of RECORD_KEYS) if (typeof entry[field] === "string") return entry[field] as string;
82
+ return null;
83
+ }
84
+
85
+ function isPrimitive(value: ProfileJson): boolean {
86
+ return value === null || typeof value !== "object";
87
+ }
88
+
89
+ /** A list of plain values with no repeats, which merges as a set. */
90
+ function isValueSet(list: readonly ProfileJson[]): boolean {
91
+ return list.every(isPrimitive) && new Set(list).size === list.length;
92
+ }
93
+
94
+ function parseJsonText(value: string): ProfileJson | undefined {
95
+ const text = value.trimStart();
96
+ if (!text.startsWith("[") && !text.startsWith("{")) return undefined;
97
+ try {
98
+ return JSON.parse(value) as ProfileJson;
99
+ } catch {
100
+ // Intentional ignore: a string that only looks like JSON is compared as text.
101
+ return undefined;
102
+ }
103
+ }
104
+
105
+ /** The edits that turn `base` into `next`. */
106
+ export function diffProfile(base: ProfileJson | undefined, next: ProfileJson | undefined): ProfileEdit[] {
107
+ const edits: ProfileEdit[] = [];
108
+ diffInto(base, next, [], edits);
109
+ return edits;
110
+ }
111
+
112
+ function diffInto(base: ProfileJson | undefined, next: ProfileJson | undefined, path: ProfileStep[], edits: ProfileEdit[]): void {
113
+ if (sameProfileJson(base, next)) return;
114
+ if (next === undefined) {
115
+ edits.push({ kind: "remove", path });
116
+ return;
117
+ }
118
+ if (isObject(base) && isObject(next)) {
119
+ for (const key of Object.keys(base)) {
120
+ if (!Object.hasOwn(next, key)) edits.push({ kind: "remove", path: [...path, { key }] });
121
+ }
122
+ for (const key of Object.keys(next)) diffInto(base[key], next[key], [...path, { key }], edits);
123
+ return;
124
+ }
125
+ if (Array.isArray(base) && Array.isArray(next)) {
126
+ const key = sharedRecordKey(base, next);
127
+ if (key) {
128
+ diffRecords(base, next, key, path, edits);
129
+ return;
130
+ }
131
+ if (isValueSet(base) && isValueSet(next)) {
132
+ const add = next.filter((entry) => !base.includes(entry));
133
+ const remove = base.filter((entry) => !next.includes(entry));
134
+ edits.push(add.length === 0 && remove.length === 0
135
+ ? { kind: "set", path, from: base, to: next }
136
+ : { kind: "members", path, from: base, to: next, add, remove });
137
+ return;
138
+ }
139
+ }
140
+ if (typeof base === "string" && typeof next === "string") {
141
+ const baseJson = parseJsonText(base);
142
+ const nextJson = parseJsonText(next);
143
+ if (baseJson !== undefined && nextJson !== undefined) {
144
+ diffInto(baseJson, nextJson, [...path, { json: true }], edits);
145
+ return;
146
+ }
147
+ }
148
+ edits.push({ kind: "set", path, from: base, to: next });
149
+ }
150
+
151
+ function diffRecords(base: ProfileJson[], next: ProfileJson[], key: RecordKey, path: ProfileStep[], edits: ProfileEdit[]): void {
152
+ const baseById = new Map(base.map((entry) => [recordId(entry, key)!, entry]));
153
+ const nextIds = next.map((entry) => recordId(entry, key)!);
154
+ const nextIdSet = new Set(nextIds);
155
+ for (const id of baseById.keys()) {
156
+ if (!nextIdSet.has(id)) edits.push({ kind: "remove", path: [...path, { id }] });
157
+ }
158
+ next.forEach((entry, index) => {
159
+ const id = nextIds[index]!;
160
+ const before = baseById.get(id);
161
+ if (before === undefined) {
162
+ edits.push({ kind: "insert", path, after: index > 0 ? nextIds[index - 1]! : null, record: entry as ProfileObject });
163
+ } else {
164
+ diffInto(before, entry, [...path, { id }], edits);
165
+ }
166
+ });
167
+ const from = [...baseById.keys()].filter((id) => nextIdSet.has(id));
168
+ const to = nextIds.filter((id) => baseById.has(id));
169
+ if (from.some((id, index) => id !== to[index])) edits.push({ kind: "order", path, from, to });
170
+ }
171
+
172
+ const REMOVED = Symbol("removed");
173
+ type Updated = ProfileJson | undefined | typeof REMOVED;
174
+
175
+ export interface ApplyProfileEditsOptions {
176
+ /**
177
+ * Who keeps a value both sides changed: the target (`keep`, the default),
178
+ * or the side the edits came from (`take`).
179
+ */
180
+ conflicts?: "keep" | "take";
181
+ }
182
+
183
+ /** `target` with every edit replayed on it; the same object when none lands. */
184
+ export function applyProfileEdits<T extends ProfileJson>(target: T, edits: readonly ProfileEdit[], options: ApplyProfileEditsOptions = {}): T {
185
+ const take = options.conflicts === "take";
186
+ let result: ProfileJson = target;
187
+ for (const edit of edits) {
188
+ const next = updateAt(result, edit.path, 0, (current) => applyLeaf(current, edit, take));
189
+ if (next !== REMOVED && next !== undefined) result = next;
190
+ }
191
+ return result as T;
192
+ }
193
+
194
+ /**
195
+ * Rewrites the value at `path` with `update`. A step that no longer resolves
196
+ * (a record or key the target removed, a string that no longer holds JSON)
197
+ * leaves the target as it is: that side's removal wins.
198
+ */
199
+ function updateAt(value: ProfileJson | undefined, path: readonly ProfileStep[], index: number, update: (current: ProfileJson | undefined) => Updated): Updated {
200
+ if (index === path.length) return update(value);
201
+ const step = path[index]!;
202
+ if ("json" in step) {
203
+ if (typeof value !== "string") return value;
204
+ const parsed = parseJsonText(value);
205
+ if (parsed === undefined) return value;
206
+ const next = updateAt(parsed, path, index + 1, update);
207
+ if (next === parsed || next === REMOVED || next === undefined) return value;
208
+ return value.includes("\n") ? JSON.stringify(next, null, 2) : JSON.stringify(next);
209
+ }
210
+ if ("key" in step) {
211
+ if (!isObject(value)) return value;
212
+ const child = value[step.key];
213
+ // Below a key the target no longer has, there is nothing left to change.
214
+ if (child === undefined && index + 1 < path.length) return value;
215
+ const next = updateAt(child, path, index + 1, update);
216
+ if (next === child) return value;
217
+ if (next === REMOVED || next === undefined) {
218
+ if (!Object.hasOwn(value, step.key)) return value;
219
+ const { [step.key]: _removed, ...rest } = value;
220
+ return rest;
221
+ }
222
+ return { ...value, [step.key]: next };
223
+ }
224
+ if (!Array.isArray(value)) return value;
225
+ const position = value.findIndex((entry) => recordId(entry, null) === step.id);
226
+ if (position < 0) return value;
227
+ const child = value[position]!;
228
+ const next = updateAt(child, path, index + 1, update);
229
+ if (next === child) return value;
230
+ if (next === REMOVED || next === undefined) return value.filter((_, at) => at !== position);
231
+ return value.map((entry, at) => (at === position ? next : entry));
232
+ }
233
+
234
+ function applyLeaf(current: ProfileJson | undefined, edit: ProfileEdit, take: boolean): Updated {
235
+ switch (edit.kind) {
236
+ case "remove":
237
+ return current === undefined ? current : REMOVED;
238
+ case "set":
239
+ if (sameProfileJson(current, edit.to)) return current;
240
+ if (take || sameProfileJson(current, edit.from)) return edit.to;
241
+ // Both sides added the same key: keep this side's values and take what only the other has.
242
+ if (edit.from === undefined && isObject(current) && isObject(edit.to)) return fillMissing(current, edit.to);
243
+ return current;
244
+ case "members": {
245
+ if (sameProfileJson(current, edit.from)) return edit.to;
246
+ if (!Array.isArray(current)) return current;
247
+ const kept = current.filter((entry) => !edit.remove.some((removed) => sameProfileJson(removed, entry)));
248
+ const added = edit.add.filter((entry) => !kept.some((present) => sameProfileJson(present, entry)));
249
+ const next = [...kept, ...added];
250
+ return sameProfileJson(next, current) ? current : next;
251
+ }
252
+ case "insert": {
253
+ if (!Array.isArray(current)) return current;
254
+ const id = recordId(edit.record, null);
255
+ const existing = current.findIndex((entry) => recordId(entry, null) === id);
256
+ if (existing >= 0) {
257
+ const present = current[existing]!;
258
+ if (!isObject(present)) return current;
259
+ const filled = fillMissing(present, edit.record);
260
+ return filled === present ? current : current.map((entry, at) => (at === existing ? filled : entry));
261
+ }
262
+ const afterIndex = edit.after === null ? -1 : current.findIndex((entry) => recordId(entry, null) === edit.after);
263
+ const at = edit.after === null ? 0 : afterIndex >= 0 ? afterIndex + 1 : current.length;
264
+ return [...current.slice(0, at), edit.record, ...current.slice(at)];
265
+ }
266
+ case "order": {
267
+ if (!Array.isArray(current)) return current;
268
+ const wanted = new Set(edit.to);
269
+ const positions: number[] = [];
270
+ const present: string[] = [];
271
+ current.forEach((entry, at) => {
272
+ const id = recordId(entry, null);
273
+ if (id !== null && wanted.has(id)) {
274
+ positions.push(at);
275
+ present.push(id);
276
+ }
277
+ });
278
+ // A list this side reordered keeps its own order.
279
+ const fromOrder = edit.from.filter((id) => present.includes(id));
280
+ if (fromOrder.some((id, at) => id !== present[at])) return current;
281
+ const toOrder = edit.to.filter((id) => present.includes(id));
282
+ const byId = new Map(current.map((entry) => [recordId(entry, null), entry]));
283
+ const next = [...current];
284
+ positions.forEach((position, at) => { next[position] = byId.get(toOrder[at]!)!; });
285
+ return sameProfileJson(next, current) ? current : next;
286
+ }
287
+ }
288
+ }
289
+
290
+ /** `present` with the keys only `added` has, recursively. */
291
+ function fillMissing(present: ProfileObject, added: ProfileObject): ProfileObject {
292
+ let result = present;
293
+ for (const [key, value] of Object.entries(added)) {
294
+ const mine = present[key];
295
+ const next = mine === undefined ? value : isObject(mine) && isObject(value) ? fillMissing(mine, value) : mine;
296
+ if (next !== mine) result = { ...result, [key]: next };
297
+ }
298
+ return result;
299
+ }
@@ -87,11 +87,20 @@ self.onmessage = (event) => {
87
87
  };
88
88
  `;
89
89
 
90
+ /** What `PRAGMA wal_checkpoint` answers: frames in the WAL, and how many of them now sit in the database. */
91
+ export interface WalCheckpointResult {
92
+ busy?: number;
93
+ log?: number;
94
+ checkpointed?: number;
95
+ }
96
+
90
97
  export interface WalCheckpointerOptions {
91
98
  /** Overrides how long the thread may owe an answer before it counts as stuck. */
92
99
  stuckAfterMs?: number;
93
100
  /** Overrides the thread's code, so a test can run one that never answers. */
94
101
  workerSource?: string;
102
+ /** Runs on the app's thread after each checkpoint, so a test can wait for one instead of the clock. */
103
+ onCheckpoint?: (result: WalCheckpointResult) => void;
95
104
  }
96
105
 
97
106
  export interface WalCheckpointer {
@@ -107,7 +116,7 @@ interface WorkerMessage {
107
116
  ms?: number;
108
117
  startedAt?: number;
109
118
  endedAt?: number;
110
- result?: { busy?: number; log?: number; checkpointed?: number };
119
+ result?: WalCheckpointResult;
111
120
  }
112
121
 
113
122
  /**
@@ -251,6 +260,7 @@ export function startWalCheckpointer(
251
260
  endedAt: Math.round(message.endedAt ?? 0),
252
261
  }, { lastStep: false });
253
262
  if (pending) schedule();
263
+ options.onCheckpoint?.(message.result ?? {});
254
264
  }
255
265
  };
256
266
  worker.onerror = (event) => {
@@ -78,7 +78,7 @@ export interface SqliteDatabaseOptions {
78
78
  * another program's lock (see access.ts). Commands and tests wait it out.
79
79
  */
80
80
  interactive?: boolean;
81
- /** Tests only: the WAL checkpointer's thread and how long it may go silent. */
81
+ /** Tests only: the WAL checkpointer's thread, how long it may go silent, and what it reports. */
82
82
  checkpointer?: WalCheckpointerOptions;
83
83
  }
84
84