diff --git a/.github/workflows/open-source-checks.yml b/.github/workflows/open-source-checks.yml index a9b41ab..4be9392 100644 --- a/.github/workflows/open-source-checks.yml +++ b/.github/workflows/open-source-checks.yml @@ -6,6 +6,7 @@ on: - '.claude-plugin/**' - 'herdr/**' - 'opencode/**' + - 'rex/**' - 'plugins/**' - 'omarchy/**' - 'raycast/**' @@ -19,6 +20,7 @@ on: - '.claude-plugin/**' - 'herdr/**' - 'opencode/**' + - 'rex/**' - 'plugins/**' - 'omarchy/**' - 'raycast/**' @@ -69,8 +71,8 @@ jobs: - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '24' - - name: Test the Herdr mod, the opencode plugin (shared quote code) and the Metrix.Bar dashboard - run: make test-herdr test-opencode test-metrix + - name: Test the Herdr mod, the opencode plugin and the Rex pane (shared quote code) and the Metrix.Bar dashboard + run: make test-herdr test-opencode test-rex test-metrix - name: Build the opencode plugin working-directory: opencode run: npm ci --no-audit --no-fund && npm run build diff --git a/.github/workflows/release-rex.yml b/.github/workflows/release-rex.yml new file mode 100644 index 0000000..309528c --- /dev/null +++ b/.github/workflows/release-rex.yml @@ -0,0 +1,51 @@ +name: Release Pulse for Rex + +# Push a tag rex-v (matching rex/package.json) to publish +# rex-pulse-ticker to npm and create a GitHub release. +on: + push: + tags: ["rex-v*"] + +permissions: + contents: write # create the GitHub release + id-token: write # npm trusted publishing (OIDC) and provenance + +jobs: + publish: + if: github.repository == 'fatwang2/Pulse' + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: npm # add required reviewers on this environment to approve each publish + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '24' + registry-url: 'https://registry.npmjs.org' + - name: Check the tag matches package.json + run: | + version="$(node -p "require('./rex/package.json').version")" + if [ "${GITHUB_REF_NAME}" != "rex-v${version}" ]; then + echo "Tag ${GITHUB_REF_NAME} does not match rex/package.json version ${version}" >&2 + exit 1 + fi + - name: Test + run: make test-herdr test-rex + - name: Publish to npm + # Authenticates with npm trusted publishing (OIDC); no token is stored anywhere. + # Skips a version that is already on npm. No build step: the package is the source. + working-directory: rex + run: | + name="$(node -p "require('./package.json').name")" + version="$(node -p "require('./package.json').version")" + if npm view "${name}@${version}" version >/dev/null 2>&1; then + echo "${name}@${version} is already published; skipping." + else + npm publish --access public --provenance + fi + - name: Create GitHub release + run: gh release create "$GITHUB_REF_NAME" --title "Pulse for Rex ${GITHUB_REF_NAME#rex-v}" --generate-notes --verify-tag + env: + GH_TOKEN: ${{ github.token }} diff --git a/AGENTS.md b/AGENTS.md index ede4bfb..724c66b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,9 +1,9 @@ # Pulse public repository -This repository hosts Pulse for Omarchy, Pulse for Claude Code, Pulse for opencode, Pulse for Herdr, Pulse for Raycast and Pulse for Metrix.Bar. Current +This repository hosts Pulse for Omarchy, Pulse for Claude Code, Pulse for opencode, Pulse for Herdr, Pulse for Rex, Pulse for Raycast and Pulse for Metrix.Bar. Current commercial Mac and website source belongs in the private Pulse repository. -- Keep `omarchy`, `plugins/claude-code`, `opencode`, `herdr`, `raycast` and `metrix` independent; follow their +- Keep `omarchy`, `plugins/claude-code`, `opencode`, `herdr`, `rex`, `raycast` and `metrix` independent; follow their scoped AGENTS.md instructions (Raycast's live in docs/raycast.md, since the Store ships everything in raycast/) and run checks appropriate to the changed edition. - Do not restore current Mac source, website source, signing material, private diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 20e2c3f..1276420 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to Pulse -This repository holds six independent open-source editions of Pulse and the +This repository holds seven independent open-source editions of Pulse and the documentation for Pulse MCP. Current commercial Mac and website development takes place elsewhere; historical Mac build instructions are linked from [the history guide](docs/history/README.md). @@ -12,6 +12,7 @@ takes place elsewhere; historical Mac build instructions are linked from | Claude Code | `plugins/claude-code` | Claude Code 2.1.287+, with Mods enabled | `make test-claude` | | opencode | `opencode` | Node.js 22+; opencode 1.15+ or 2.x for runtime checks | `make test-opencode`, then `npm run build` in `opencode/` | | Herdr | `herdr` | Node.js 22+; Herdr for runtime checks | `make test-herdr` | +| Rex | `rex` | Node.js 22+; Rex for runtime checks | `make test-rex` | | Metrix.Bar | `metrix` | Node.js 22+; Metrix.Bar with its local API for runtime checks | `make test-metrix` | | Omarchy | `omarchy` | Node.js 22+ for reducer tests; Omarchy 4 / Qt for runtime checks | `make test-omarchy` | | Raycast | `raycast` | Node.js 22+; Raycast for runtime checks | `make test-raycast` | @@ -52,8 +53,9 @@ What the checks cover: - **Claude Code** tests use its native Mods harness with mocked host APIs and make no model calls. For type checking, follow its README's declaration-generation instructions. -- **opencode** and **Herdr** test their shared quote and watchlist code with - `node --test`; the opencode copy must match Herdr's, and a test checks it. +- **opencode**, **Herdr** and **Rex** test their shared quote and watchlist code + with `node --test`; the opencode and Rex copies must match Herdr's, and tests + check it. Rex also tests that every line it draws fits its pane. - **Metrix.Bar** tests check that `metrix/index.json` matches `pulse.bar` (its SHA-256 and version), the declared hosts, and the Worker's symbol, search and formatting rules. Rebuild the index after every change to `pulse.bar`; see @@ -75,6 +77,7 @@ change works, try it there: | Claude Code | Load the plugin in Claude Code, and in Claude Desktop's Code tab if the change touches the panel | | opencode | Install the packed package in a real opencode v1 and v2, not only from a checkout | | Herdr | `herdr-app check` on the mod, then run it in Herdr; each `preview.png` is a real screenshot | +| Rex | `rex config check` on an `init.lua` that loads `rex/lua/pulse.lua`, then `rex do --action pulse_open` and a look at the pane and its layer | | Metrix.Bar | `POST /v0/validate` and `POST /v0/check` with fixtures and steps, then the installed dashboard | | Omarchy | The bar and panel in an Omarchy 4 session | | Raycast | `npm run dev` in `raycast/`, then the command in Raycast | @@ -88,7 +91,7 @@ acceptance. Each edition is released on its own; versions and changelogs stay separate. Existing `v0.*` tags belong to the historical Mac app and must not be reused for open-source releases. Release steps are in each edition's AGENTS.md; for -example, opencode publishes to npm from an `opencode-v*` tag, Raycast is +example, opencode and Rex publish to npm from `opencode-v*` and `rex-v*` tags, Raycast is submitted to the Store only from the owner's Mac, and Metrix.Bar users receive whatever `metrix/index.json` on `main` describes. See also the [transition notes](docs/repository-transition.md). @@ -96,7 +99,7 @@ whatever `metrix/index.json` on `main` describes. See also the ## Issues and changes Name the edition when you report an issue: **Claude Code**, **opencode**, -**Herdr**, **Metrix.Bar**, **Omarchy**, **Raycast**, **Pulse MCP**, **current +**Herdr**, **Rex**, **Metrix.Bar**, **Omarchy**, **Raycast**, **Pulse MCP**, **current commercial Mac** or **historical Mac**. Include the relevant application and host versions and the steps to reproduce. Remove credentials and private financial information from logs and screenshots. Report security issues diff --git a/Makefile b/Makefile index a9d9139..bcaf72a 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ -.PHONY: test test-claude test-omarchy test-herdr test-opencode test-raycast test-metrix validate +.PHONY: test test-claude test-omarchy test-herdr test-opencode test-rex test-raycast test-metrix validate -test: test-claude test-omarchy test-herdr test-opencode test-raycast test-metrix +test: test-claude test-omarchy test-herdr test-opencode test-rex test-raycast test-metrix test-claude: claude plugin validate plugins/claude-code @@ -16,6 +16,9 @@ test-herdr: test-opencode: node --test opencode/tests/*.test.mjs +test-rex: + node --test rex/tests/*.test.mjs + test-metrix: node --test metrix/tests/*.test.mjs diff --git a/README.md b/README.md index 4097a94..128e173 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ server built into Pulse for Mac. | **Pulse for Claude Code** | Claude Code, Claude Desktop's Code tab | Prices above the prompt, `/pulse` panel to manage tickers | Open source, MIT | [Guide](plugins/claude-code/README.md) | | **Pulse for opencode** | opencode | Sidebar watchlist with today's line and a detail view, quote band | Open source, MIT, on npm | [Guide](opencode/README.md) | | **Pulse for Herdr** | Herdr | Watchlist docked beside your agents, with a detail view | Open source, MIT | [Guide](herdr/README.md) | +| **Pulse for Rex** | Rex | Watchlist in a pane beside your agents, with the selected ticker's chart and a detail layer | Open source, MIT | [Guide](rex/README.md) | | **Pulse for Metrix.Bar** | Metrix.Bar menu bar | Ticker in the menu bar, watchlist with search and a detail view | Open source, MIT | [Guide](metrix/README.md) | | **Pulse for Omarchy** | Omarchy 4 bar (Linux) | Prices in the bar, named watchlists, search, charts | Open source, MIT | [Guide](omarchy/README.md) | | **Pulse for Raycast** | Raycast | Search any symbol by ticker or name, with its price and today's chart | Open source, MIT, in Raycast Store review | [Guide](raycast/README.md) | @@ -118,6 +119,22 @@ Read ~/.config/herdr-app/AGENTS.md, then add this layout: https://github.com/fat See the [Herdr guide](herdr/README.md) for the mod on its own, usage and privacy. +## Pulse for Rex + +A [Rex](https://www.superlogical.com/rex) pane: a stock and crypto watchlist +beside your agents, with the selected ticker's day below the list, and a floating layer with its chart, open, high, low and +previous close. Opened from Rex's command palette. + +Pulse for Rex: the watchlist with the selected ticker's day below it + +```sh +npm install --global rex-pulse-ticker +pulse-rex install +``` + +Then press **cmd+shift+p** in Rex and run **Pulse: Open Watchlist**. See the +[Rex guide](rex/README.md) for usage and privacy. + ## Pulse for Metrix.Bar A [Metrix.Bar](https://metrix.bar) dashboard: your first ticker in the menu diff --git a/rex/AGENTS.md b/rex/AGENTS.md new file mode 100644 index 0000000..53d202b --- /dev/null +++ b/rex/AGENTS.md @@ -0,0 +1,40 @@ +# Pulse for Rex + +- A Node CLI (npm package `rex-pulse-ticker`, bin `pulse-rex`) plus + `lua/pulse.lua`, which Rex's `init.lua` loads. Rex lets config draw no UI, so + the watchlist is a terminal program in a pane; the Lua only registers + `rex.action`s and runs `pulse-rex`. No runtime dependencies. +- `src/quotes.js` and `src/watchlist.js` are copies of the Herdr mod's + (`herdr/pulse/mods/pulse/`): only the header comment and `PULSE_URLS` differ, + and a test checks it. Change all copies together. Keep them, `src/format.js` + and `src/store.js` free of Rex calls so `node --test` can run them. +- `src/format.js` is pure: state in, lines out. Every line must fit its pane + width (a test draws many sizes); measure with `cells`, cut with `fit`. +- `pulse-rex install` only adds or replaces the block between + `-- >>> pulse >>>` and `-- <<< pulse <<<` in Rex's `init.lua`, runs + `rex config check`, and restores the file when the check fails. Never touch + the rest of the file, and never rewrite it on start or on use. +- Pane width: Rex sizes splits by fraction and the app evens out a new split + after it shows, so `pulse_open` passes `--beside` and `--ratio` and the pane + calls `session.resize_pane` itself after it starts. +- The only hosts are `query1.finance.yahoo.com` and `data-api.binance.vision`. + The only program is `rex` (layers, resizing, config check and reload). Pulse + for Mac links are OSC 8 hyperlinks; Pulse never opens a browser itself. Keep + README and code in step on hosts, programs, storage and behavior. +- Promote Pulse for Mac only, modestly (the footer link, the detail's card, + the README); name no other edition. Links carry `utm_source=rex`. +- Respect Yahoo cooldowns; never show cached data as fresh or unknown delay as + real time. Crypto never waits on Yahoo. +- `preview.png` must be a screenshot of the real pane running in Rex. +- Test in a real Rex before release: `rex config check` on an `init.lua` that + loads the Lua, `rex do --action pulse_open`, and a look at the + pane, the layer and the band. +- Releases: bump `version` in `package.json` (the User-Agent reads it), merge + to main, then push the tag `rex-v`. `.github/workflows/release-rex.yml` + checks the tag, tests, publishes `rex-pulse-ticker` to npm with provenance + through npm trusted publishing (repository `fatwang2/Pulse`, workflow + `release-rex.yml`, environment `npm`; no token is stored) and creates a + GitHub release. A version npm already has is skipped. +- `pulse-rex install` writes node and the package through a version manager's + stable link when there is one (`…/node/current/bin/node`), so upgrading node + doesn't break Rex's config. diff --git a/rex/LICENSE b/rex/LICENSE new file mode 100644 index 0000000..794bd2f --- /dev/null +++ b/rex/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 fatwang2 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/rex/README.md b/rex/README.md new file mode 100644 index 0000000..cfcc97a --- /dev/null +++ b/rex/README.md @@ -0,0 +1,95 @@ +# Pulse for Rex + +A stock and crypto watchlist in a [Rex](https://www.superlogical.com/rex) pane +beside your agents, from the makers of +[Pulse for Mac](https://www.pulseticker.app/?utm_source=rex&utm_medium=readme). +Each ticker shows its price and its change. The selected ticker's day fills +the rest of the pane: a chart, the open, high, low and +previous close, and where the numbers come from. Press Enter for the same day +in a floating layer. Stocks and indices come from Yahoo Finance, crypto pairs +(`BTC/USDT`) from Binance's public Spot data. Squeezed to six rows or fewer, +the pane draws a one-line quote band instead. + +![Pulse for Rex: the watchlist with the selected ticker's day below it](preview.png) + +## Install + +Needs Node.js 18.17 or later and Rex's `rex` command on your `PATH`. + +```sh +npm install --global rex-pulse-ticker +pulse-rex install +``` + +`pulse-rex install` adds one marked block to the end of Rex's `init.lua` +(`~/.config/rex/init.lua`, or where `REX_CONFIG` points), checks it with +`rex config check`, and reloads Rex's config. If the check fails, the file is +put back as it was. `pulse-rex uninstall` removes the block. + +Then press **cmd+shift+p** in Rex and type **Pulse**: + +| Action | Name | What it does | +| --- | --- | --- | +| Pulse: Open Watchlist | `pulse_open` | Opens the watchlist about 48 columns wide beside the focused pane, or focuses the one already open in this window | +| Pulse: Add Ticker… | `pulse_add` | A small prompt for a ticker; `rex do pulse_add symbol=0700.HK` adds one directly | +| Pulse: Refresh Quotes | `pulse_refresh` | One round now in every open Pulse pane | +| Pulse: Pause or Resume | `pulse_pause` | Stops automatic refresh, or starts it again | + +No keys are bound by default. To bind one, add a line after the Pulse block in +`init.lua`, such as `rex.bind("cmd+shift+u", "pulse_open")`, or pass `keys` to +`setup`: `keys = { open = "cmd+shift+u" }`. `width = 56` makes the pane wider. + +Without the palette, `pulse-rex` runs the watchlist in any terminal. + +## Use + +- It starts with `AAPL`, `NVDA`, `^GSPC` and `BTC/USDT`. +- `↑` `↓` (or `j` `k`, or the mouse wheel) select a ticker; a click selects + one, a second click opens it. +- `Enter` opens the selected ticker's day in a floating layer; `Esc` closes it. +- `a` adds a ticker: `AAPL`, `0700.HK`, `^GSPC`, `BTC/USDT`. `x` removes the + selected one. +- `r` refreshes now; `p` pauses or resumes automatic refresh; `q` closes the pane. +- From a shell: `pulse-rex add NVDA`, `pulse-rex remove NVDA`, + `pulse-rex pause`, `pulse-rex resume`, `pulse-rex refresh`, `pulse-rex list`. + Open panes pick changes up within a second. + +Quotes refresh 60 seconds after each round. Stock prices are Yahoo's +regular-session quotes; exchange delays vary and are shown when Yahoo reports +them. Crypto changes and lines are 24-hour. A quote from an earlier day +carries its date. Early in a session, today's line only reaches as far as the +day has gone. + +Want quotes in your menu bar, with charts and positions? That's +[Pulse for Mac](https://www.pulseticker.app/?utm_source=rex&utm_medium=readme). + +## Privacy + +The watchlist is saved in `~/.config/pulse-rex/watchlist.json` (or under +`XDG_CONFIG_HOME`). Watching a ticker sends it to Yahoo Finance; watching a +pair sends it to Binance. Pulse contacts no other host and has no account or +analytics. The Pulse for Mac links are terminal hyperlinks to +`https://www.pulseticker.app/`, tagged `utm_source=rex&utm_medium=plugin`; +your terminal opens them only when you click one. The only program Pulse runs +is `rex`, to open its layers and set its pane's width. See the +[Pulse privacy policy](https://www.pulseticker.app/privacy). + +## How it fits into Rex + +Rex has no plugin UI of its own, so Pulse is a terminal program in a pane, and +`lua/pulse.lua` is the glue Rex's config loads: four `rex.action`s that open +the pane with `rex.session.new_split` and change the saved list by running +`pulse-rex`. The pane sizes itself with `session.resize_pane` once Rex shows +it, and opens the detail with `session.new_layer`. + +## Development + +```sh +node --test rex/tests/*.test.mjs +``` + +The tests cover drawing (every line fits its pane at every size, the chart, +the band, wide characters), keys, the shared watchlist file, the `init.lua` +block, and that `quotes.js` and `watchlist.js` match the Herdr mod's. The +Lua needs Rex itself: write an `init.lua` that `dofile`s `rex/lua/pulse.lua` +and run `rex config check` on it. diff --git a/rex/bin/pulse-rex.js b/rex/bin/pulse-rex.js new file mode 100755 index 0000000..82a8c06 --- /dev/null +++ b/rex/bin/pulse-rex.js @@ -0,0 +1,107 @@ +#!/usr/bin/env node +// pulse-rex: the Pulse watchlist for Rex, and the commands its palette actions run. +import { realpathSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { QuoteError } from "../src/quotes.js"; +import { Watchlist } from "../src/watchlist.js"; +import { createStore } from "../src/store.js"; + +const HELP = `pulse-rex — stock and crypto quotes beside your agents in Rex + +Usage: + pulse-rex install add Pulse to Rex's command palette (edits Rex's init.lua) + pulse-rex uninstall take it out again + pulse-rex run the watchlist in this terminal + pulse-rex add SYMBOL... add tickers: AAPL, 0700.HK, ^GSPC, BTC/USDT + pulse-rex remove SYMBOL... remove tickers + pulse-rex pause | resume | toggle-pause + pulse-rex refresh ask open Pulse panes for a round now + pulse-rex list print the watchlist + pulse-rex --version +`; + +const self = [process.execPath, realpathSync(fileURLToPath(import.meta.url))]; +const [command = "tui", ...args] = process.argv.slice(2); + +function editor() { + const store = createStore(); + const offline = () => Promise.reject(new Error("not used")); + return { store, watch: new Watchlist({ load: store.load, save: store.save, fetch: offline, now: Date.now, sleep: offline, changed() {} }) }; +} + +function fail(message) { + process.stderr.write(`${message}\n`); + process.exit(1); +} + +async function main() { + switch (command) { + case "tui": { + const { runPane } = await import("../src/tui.js"); + const option = (name) => { const at = args.indexOf(name); return at === -1 ? undefined : args[at + 1]; }; + const ratio = Number(option("--ratio")); + const beside = option("--beside"); + return runPane(self, beside && ratio > 0 && ratio < 1 ? { beside, ratio } : null); + } + case "detail": { + const { runDetail } = await import("../src/tui.js"); + const at = args.indexOf("--quote"); + return runDetail(at === -1 ? "" : args[at + 1]); + } + case "prompt": { + const { runPrompt } = await import("../src/tui.js"); + return runPrompt(); + } + case "add": case "remove": { + if (!args.length) { + if (command === "add" && process.stdin.isTTY) { + const { runPrompt } = await import("../src/tui.js"); + return runPrompt(); + } + fail(`Usage: pulse-rex ${command} SYMBOL...`); + } + const { watch } = editor(); + for (const symbol of args) { + try { console.log(watch[command](command === "remove" ? symbol.trim().toUpperCase() : symbol)); } catch (error) { + fail(error instanceof QuoteError ? error.message : String(error?.message ?? error)); + } + } + return; + } + case "pause": case "resume": case "toggle-pause": { + const { watch } = editor(); + const paused = command === "toggle-pause" ? !watch.preferences.paused : command === "pause"; + console.log(watch.pause(paused)); + return; + } + case "refresh": { + createStore().requestRefresh(); + console.log("Asked open Pulse panes to refresh."); + return; + } + case "list": { + const { watch } = editor(); + console.log(watch.preferences.symbols.join("\n") || "Your watchlist is empty."); + if (watch.preferences.paused) console.log("(automatic refresh is paused)"); + return; + } + case "install": case "uninstall": { + const installer = await import("../src/install.js"); + try { console.log(installer[command]()); } catch (error) { fail(String(error?.message ?? error)); } + return; + } + case "--version": case "-v": case "version": { + const { VERSION } = await import("../src/tui.js"); + console.log(VERSION); + return; + } + case "--help": case "-h": case "help": + process.stdout.write(HELP); + return; + default: + process.stderr.write(HELP); + process.exit(2); + } +} + +main().catch((error) => fail(String(error?.stack ?? error))); diff --git a/rex/lua/pulse.lua b/rex/lua/pulse.lua new file mode 100644 index 0000000..b83930f --- /dev/null +++ b/rex/lua/pulse.lua @@ -0,0 +1,154 @@ +-- Pulse for Rex: a stock and crypto watchlist beside your agents. +-- +-- `pulse-rex install` loads this from Rex's config (init.lua): +-- +-- dofile("/path/to/lua/pulse.lua").setup({ bin = { "/path/to/node", "/path/to/pulse-rex.js" } }) +-- +-- The watchlist is a terminal program (`pulse-rex`) in a pane. These actions +-- open it, and change the saved list through the same program; every open +-- Pulse pane picks a change up within a second. +-- +-- setup options: +-- bin the command that runs pulse-rex, as a list +-- width columns for the Pulse pane (default 48) +-- keys { open = "cmd+shift+u", add = "...", refresh = "...", pause = "..." }; none by default + +local M = {} + +local TERMINAL = "com.superlogical.terminal" +local SHELL = "com.superlogical.terminal.shell" +local LABEL = "Pulse" + +function M.setup(opts) + opts = opts or {} + local bin = opts.bin or { "pulse-rex" } + if type(bin) == "string" then bin = { bin } end + local width = opts.width or 48 + + local function argv(...) + local out = {} + for _, part in ipairs(bin) do out[#out + 1] = part end + for _, part in ipairs({ ... }) do out[#out + 1] = part end + return out + end + + -- Pulse runs on this Mac; a pane on a remote host would have no pulse-rex. + local function local_only(ctx) + if ctx.server ~= nil then + error("Pulse: open it from a session on this Mac. Remote hosts aren't supported yet.", 0) + end + end + + local function run(...) + local result, err = rex.exec(argv(...), { timeout = 10 }) + if result == nil then + error("Pulse: couldn't run pulse-rex (" .. tostring(err) .. "). Reinstall it, then run `pulse-rex install`.", 0) + end + if not result.ok then + local text = result.stderr ~= "" and result.stderr or result.stdout + error("Pulse: " .. text:gsub("%s+$", ""), 0) + end + return result + end + + -- The Pulse pane already in the focused pane's window, if there is one. + local function existing(ctx) + local listed = rex.session.list_blocks{} + if type(listed) ~= "table" or type(listed.blocks) ~= "table" then return nil end + local window + for _, block in ipairs(listed.blocks) do + if block.block_id == ctx.block_id then window = block.window_id end + end + for _, block in ipairs(listed.blocks) do + if block.label == LABEL and block.placement == "placed" and block.window_id == window then + return block.block_id + end + end + return nil + end + + rex.action{ + name = "pulse_open", + title = "Pulse: Open Watchlist", + description = "Stock and crypto quotes in a pane beside this one, with today's line for each ticker.", + category = "Pulse", + keywords = "pulse stocks crypto quotes ticker watchlist market price", + run = function(ctx) + local_only(ctx) + local found = existing(ctx) + if found ~= nil then + rex.session.focus_block{ block_id = found } + return + end + if ctx.block_id == nil then + local layout = { block = { flavor = SHELL, label = LABEL, options = { command = argv() } } } + local _, err = rex.session.new_window{ label = LABEL, layout = layout, focus = true } + if err ~= nil then error("Pulse: couldn't open a tab: " .. tostring(err), 0) end + return + end + -- Rex sizes splits by fraction, so turn the wanted width into one. The + -- app evens out a new split once it shows, so pulse-rex moves the border + -- itself after it starts (--beside, --ratio). + local command = argv() + local size = rex.block.call(TERMINAL, "size", { block_id = ctx.block_id }) + if type(size) == "table" and type(size.columns) == "number" and size.columns > width * 1.5 then + local ratio = math.max(0.3, math.min(0.85, (size.columns - width - 1) / size.columns)) + command = argv("tui", "--beside", ctx.block_id, "--ratio", string.format("%.4f", ratio)) + end + local _, err = rex.session.new_split{ + anchor_id = ctx.block_id, + direction = "horizontal", + side = "after", + focus = true, + layout = { block = { flavor = SHELL, label = LABEL, options = { command = command } } }, + } + if err ~= nil then error("Pulse: couldn't open a pane: " .. tostring(err), 0) end + end, + } + + rex.action{ + name = "pulse_add", + title = "Pulse: Add Ticker…", + description = "Add a stock, index or crypto pair to the watchlist: AAPL, 0700.HK, ^GSPC, BTC/USDT.", + category = "Pulse", + keywords = "pulse add ticker symbol stock crypto watchlist", + args = { symbol = "string?" }, + run = function(ctx, args) + if args.symbol ~= nil and args.symbol ~= "" then + run("add", args.symbol) + return + end + local_only(ctx) + local _, err = rex.session.new_layer{ + bounds = { 0.3, 0.3, 0.4, 0.2 }, + focus = true, + layout = { block = { flavor = SHELL, label = "Pulse · Add", options = { command = argv("prompt") } } }, + } + if err ~= nil then error("Pulse: couldn't open the prompt: " .. tostring(err), 0) end + end, + } + + rex.action{ + name = "pulse_refresh", + title = "Pulse: Refresh Quotes", + description = "Fetch every ticker now in the open Pulse panes. Yahoo's cooldown still applies.", + category = "Pulse", + keywords = "pulse refresh reload quotes now", + run = function() run("refresh") end, + } + + rex.action{ + name = "pulse_pause", + title = "Pulse: Pause or Resume", + description = "Stop automatic refresh, or start it again. Refresh Quotes still works while paused.", + category = "Pulse", + keywords = "pulse pause resume stop start auto refresh", + run = function() run("toggle-pause") end, + } + + for short, key in pairs(opts.keys or {}) do + rex.bind(key, "pulse_" .. short) + end +end + +return M diff --git a/rex/package.json b/rex/package.json new file mode 100644 index 0000000..b4cce3a --- /dev/null +++ b/rex/package.json @@ -0,0 +1,43 @@ +{ + "name": "rex-pulse-ticker", + "version": "0.1.0", + "description": "Stock and crypto quotes in a Rex pane beside your agents, from the makers of Pulse for Mac", + "type": "module", + "license": "MIT", + "author": "fatwang2", + "homepage": "https://github.com/fatwang2/Pulse/tree/main/rex#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/fatwang2/Pulse.git", + "directory": "rex" + }, + "bugs": { + "url": "https://github.com/fatwang2/Pulse/issues" + }, + "keywords": [ + "rex", + "terminal", + "tui", + "stocks", + "crypto", + "ticker", + "watchlist" + ], + "bin": { + "pulse-rex": "bin/pulse-rex.js" + }, + "files": [ + "bin", + "src", + "lua", + "preview.png", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=18.17" + }, + "scripts": { + "test": "node --test tests/*.test.mjs" + } +} diff --git a/rex/preview.png b/rex/preview.png new file mode 100644 index 0000000..a7e8e78 Binary files /dev/null and b/rex/preview.png differ diff --git a/rex/src/format.js b/rex/src/format.js new file mode 100644 index 0000000..5577abc --- /dev/null +++ b/rex/src/format.js @@ -0,0 +1,356 @@ +// What the Pulse pane and the detail layer print: plain functions from the +// watchlist's state to lines of terminal text. No Rex imports and no I/O, so +// tests run it under Node. Colors come in as a palette, so tests can pass one +// without escape codes. +import { + PULSE_URLS, SESSION_LABELS, formatBandPrice, formatChange, formatPrice, formatStaleDate, formatTime, + isCryptoPair, marketSession, +} from "./quotes.js"; + +const BARS = "▁▂▃▄▅▆▇█"; +const ESC = "\x1b["; + +// --------------------------------------------------------------------------- +// Colors + +const rgb = (hex) => `38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}`; +const sgr = (code) => (text) => (text ? `${ESC}${code}m${text}${ESC}0m` : ""); + +/** Terminal colors, so the pane follows the Rex theme; Pulse's blue is the one fixed color. */ +export function palette(dark = true) { + return { + bold: sgr("1"), + dim: sgr("2"), + brand: sgr(rgb(dark ? "#6AB0FF" : "#1066C6")), + brandBold: sgr(`1;${rgb(dark ? "#6AB0FF" : "#1066C6")}`), + up: sgr("32"), + down: sgr("31"), + warn: sgr("33"), + // A faint wash of Pulse's blue behind the row, kept through the row's own colors. + selected: (text) => { + const wash = `48;2;${dark ? "27;42;61" : "227;238;251"}`; + return `${ESC}${wash}m${text.replaceAll(`${ESC}0m`, `${ESC}0;${wash}m`)}${ESC}0m`; + }, + link: (url, text) => `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\`, + }; +} + +/** The same palette with every color left out. */ +export const PLAIN = { + bold: (t) => t, dim: (t) => t, brand: (t) => t, brandBold: (t) => t, up: (t) => t, down: (t) => t, + warn: (t) => t, selected: (t) => t, link: (_url, t) => t, +}; + +const tone = (colors, value) => (value === null || value === undefined ? colors.dim : value >= 0 ? colors.up : colors.down); + +// --------------------------------------------------------------------------- +// Measuring + +const ANSI = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\]8;;[^\x1b]*\x1b\\/g; + +export const strip = (text) => text.replace(ANSI, ""); + +/** East Asian wide and fullwidth characters take two cells. */ +function wide(code) { + return (code >= 0x1100 && code <= 0x115f) || (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) + || (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xfe30 && code <= 0xfe4f) + || (code >= 0xff00 && code <= 0xff60) || (code >= 0xffe0 && code <= 0xffe6) || (code >= 0x1f300 && code <= 0x1faff) + || (code >= 0x20000 && code <= 0x3fffd); +} + +/** The cells `text` fills once printed, escape codes left out. */ +export function cells(text) { + let width = 0; + for (const char of strip(text)) width += wide(char.codePointAt(0)) ? 2 : 1; + return width; +} + +/** Plain text cut to `width` cells, ending in "…" when cut. */ +export function fit(text, width) { + if (width <= 0) return ""; + if (cells(text) <= width) return text; + let out = ""; + let used = 0; + for (const char of text) { + const size = wide(char.codePointAt(0)) ? 2 : 1; + if (used + size > width - 1) break; + out += char; + used += size; + } + return out + "…"; +} + +/** A line with escape codes cut to `width` cells, keeping its codes and closing any color it cut through. */ +export function clip(line, width) { + if (cells(line) <= width) return line; + let out = ""; + let used = 0; + const token = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\]8;;[^\x1b]*\x1b\\|[\s\S]/gu; + for (const [part] of line.matchAll(token)) { + if (part.startsWith("\x1b")) { out += part; continue; } + const size = wide(part.codePointAt(0)) ? 2 : 1; + if (used + size > width) break; + out += part; + used += size; + } + return `${out}${ESC}0m\x1b]8;;\x1b\\`; +} + +/** Plain text broken into lines of at most `width` cells, at spaces where it can be. */ +export function wrap(text, width) { + const lines = []; + let line = ""; + for (const word of text.split(/\s+/).filter(Boolean)) { + const next = line ? `${line} ${word}` : word; + if (cells(next) <= width) { line = next; continue; } + if (line) lines.push(line); + line = cells(word) <= width ? word : fit(word, width); + } + if (line) lines.push(line); + return lines; +} + +const padEnd = (text, width) => text + " ".repeat(Math.max(0, width - cells(text))); +const padStart = (text, width) => " ".repeat(Math.max(0, width - cells(text))) + text; +/** `left` and `right` on one line of `width` cells, the right one flush with the edge. */ +const spread = (left, right, width) => padEnd(left, width - cells(right)) + right; + +// --------------------------------------------------------------------------- +// Lines and charts + +/** `width` averages of `series`, one per column; a short series is stretched. */ +function columns(series, width) { + const out = []; + for (let i = 0; i < width; i++) { + const from = Math.floor((i * series.length) / width); + const to = Math.max(from + 1, Math.floor(((i + 1) * series.length) / width)); + const slice = series.slice(from, Math.min(to, series.length)); + out.push(slice.reduce((sum, value) => sum + value, 0) / slice.length); + } + return out; +} + +/** + * The day as `height` rows of `width` cells, top row first: filled columns up to + * each price, and the previous close as a dotted rule where no column covers it. + * Each row is a list of runs, `{ text, kind }` with kind "bar", "rule" or "space". + */ +export function chartRows(series, reference, width, height) { + if (!Array.isArray(series) || series.length < 2 || width < 2 || height < 1) return []; + const values = columns(series, Math.min(width, series.length)); + const scale = typeof reference === "number" && reference > 0 ? [...values, reference] : values; + let min = Math.min(...scale); + let max = Math.max(...scale); + if (max - min < max * 1e-9) { min -= 1; max += 1; } + // Headroom: below, so the lowest price still shows a sliver of bar; above, so + // the day's high stays clear of the price line over the chart. + const span = max - min; + min -= span * 0.06; + max += span * 0.15; + const level = (value) => ((value - min) / (max - min)) * height; + const ruleRow = scale.length > values.length ? Math.min(height - 1, Math.floor(level(reference))) : -1; + const rows = []; + for (let row = height - 1; row >= 0; row--) { + const runs = []; + const push = (text, kind) => { + const last = runs.at(-1); + if (last?.kind === kind) last.text += text; else runs.push({ text, kind }); + }; + for (let column = 0; column < width; column++) { + const fill = column < values.length ? level(values[column]) - row : 0; + if (fill >= 1) push("█", "bar"); + else if (fill > 0) push(BARS[Math.max(0, Math.ceil(fill * BARS.length) - 1)], "bar"); + else if (row === ruleRow) push("┄", "rule"); + else push(" ", "space"); + } + rows.push(runs); + } + return rows; +} + +function paintChart(rows, colors, change) { + const bar = tone(colors, change); + return rows.map((runs) => runs.map((run) => (run.kind === "bar" ? bar(run.text) : run.kind === "rule" ? colors.dim(run.text) : run.text)).join("")); +} + +// --------------------------------------------------------------------------- +// Words + +/** "Delay 15m", "" for real time, and never real time when the source didn't say. */ +function delayText(quote) { + if (isCryptoPair(quote.symbol)) return ""; + if (quote.delaySeconds === null || quote.delaySeconds === undefined) return "Delay unknown"; + return quote.delaySeconds > 0 ? `Delay ${Math.round(quote.delaySeconds / 60)}m` : ""; +} + +function subtitle(symbol, quote, error, now) { + if (!quote) return { text: error ?? "", warn: Boolean(error) }; + if (error) return { text: `Cached quote · ${error}`, warn: true }; + const stale = formatStaleDate(quote.timestamp, now); + const delay = delayText(quote); + return { + text: [quote.name !== symbol ? quote.name : "", stale ? `As of ${stale}` : "", delay === "Delay unknown" ? "" : delay] + .filter(Boolean).join(" · "), + warn: false, + }; +} + +const sources = (symbols) => (symbols.some(isCryptoPair) + ? "Yahoo Finance · Binance Spot (24h change)" + : "Yahoo Finance · Regular-session quotes · Exchange delays vary"); + +export const KEYS = "↑↓ select · ⏎ open · a add · x remove · r refresh · p pause · q quit"; +const SHORT_KEYS = "↑↓ ⏎ open · a add · x remove · r · p · q"; +const keysLine = (width) => (cells(KEYS) <= width ? KEYS : fit(SHORT_KEYS, width)); + +// --------------------------------------------------------------------------- +// The pane + +/** A pane this many rows tall or less draws the one-line band. Rex's shortest pane is five rows. */ +export const BAND_ROWS = 6; + +/** + * The Pulse pane as lines of at most `width` cells and at most `height` lines. + * `state` is `{ symbols, quotes, errors, paused, loading, message, selected, + * adding, input, notice, error, now }`. Returns `{ lines, rows }`, where `rows` + * maps a line number to the index of the ticker printed there, for clicks. + */ +export function pane(state, width, height, colors = PLAIN) { + if (height <= BAND_ROWS) return { lines: [band(state, width, colors)], rows: {} }; + const W = Math.max(1, width - 2); + const indent = (line) => clip(` ${line}`, width); + const rule = colors.dim("─".repeat(W)); + const { symbols } = state; + + const top = []; + const keysHint = colors.dim("r Refresh p " + (state.paused ? "Resume" : "Pause")); + const title = `${colors.brandBold("◆ Pulse")} ${colors.dim(`${symbols.length} ticker${symbols.length === 1 ? "" : "s"}`)}`; + top.push(cells(title) + cells(keysHint) + 2 <= W ? spread(title, keysHint, W) : title); + top.push(state.loading ? colors.brand(fit("● Refreshing quotes…", W)) + : state.paused ? colors.warn(fit("● Auto-refresh paused", W)) : colors.up(fit("● Auto-refresh every 60s", W))); + if (state.adding) { + top.push(`${colors.brand("›")} ${fit(state.input, W - 4)}${colors.brand("▏")}`); + top.push(colors.dim(fit("Enter adds · Esc cancels · AAPL, 0700.HK, ^GSPC, BTC/USDT", W))); + } else { + top.push(colors.dim(fit("+ Add a ticker (a): AAPL, 0700.HK, BTC/USDT", W))); + } + const note = state.error ? colors.down(fit(state.error, W)) + : state.message ? colors.warn(fit(state.message, W)) + : state.notice ? colors.dim(fit(state.notice, W)) : ""; + if (note) top.push(note); + top.push(rule); + + const footer = [ + rule, + colors.dim(fit(sources(symbols), W)), + `${colors.link(PULSE_URLS.panel, `${colors.brandBold("Pulse for Mac")} ${colors.brand("pulseticker.app ↗")}`)}${cells("Pulse for Mac pulseticker.app ↗") + 3 <= W - 20 ? colors.dim(fit(" Menu bar charts and positions", W - 31)) : ""}`, + colors.dim(keysLine(W)), + ]; + + // The list, scrolled to keep the selection in view when it doesn't fit. + const list = []; + const listRows = {}; + const room = Math.max(2, height - top.length - footer.length); + const fitsAll = symbols.length * 2 <= room; + const visible = Math.max(1, Math.floor(room / 2)); + const first = fitsAll ? 0 : Math.min(Math.max(0, state.selected - Math.floor(visible / 2)), Math.max(0, symbols.length - visible)); + if (!symbols.length) list.push(colors.dim(fit("Your watchlist is empty. Press a to add a ticker.", W))); + for (let i = first; i < symbols.length && list.length + 2 <= room; i++) { + const [one, two] = tickerLines(symbols[i], state, W, colors); + listRows[top.length + list.length] = i; + listRows[top.length + list.length + 1] = i; + const mark = (line) => (i === state.selected ? colors.selected(padEnd(line, W)) : line); + list.push(mark(one), mark(two)); + } + + // The selected ticker's day fills what's left, when there is enough of it. + const spare = height - top.length - list.length - footer.length; + const chosen = symbols[state.selected]; + const quote = chosen ? state.quotes[chosen] : null; + let detail = []; + if (quote && spare >= 13) { + // Terminal cells are about twice as tall as wide: half the width in rows draws a square chart. + const chartHeight = Math.min(Math.round(W / 2), spare - 10); + detail = [rule, ...detailBlock(quote, state.errors[chosen], state.now, W, chartHeight, colors)]; + } + // The footer follows the content; what's left of a tall pane stays empty below it. + const lines = [...top, ...list, ...detail, ...footer].slice(0, height).map(indent); + return { lines, rows: listRows }; +} + +function tickerLines(symbol, state, W, colors) { + const quote = state.quotes[symbol]; + const error = state.errors[symbol]; + const change = quote ? quote.changePercent : null; + const paint = tone(colors, change); + const price = quote ? formatPrice(quote) : state.paused ? "Not fetched" : "Waiting…"; + const symbolWidth = Math.max(4, W - cells(price) - 1); + const one = spread(colors.bold(fit(symbol, symbolWidth)), quote ? price : colors.dim(price), W); + const sub = subtitle(symbol, quote, error, state.now); + const changeText = formatChange(change); + const text = fit(sub.text, W - cells(changeText) - 1); + const two = spread(sub.warn ? colors.warn(text) : colors.dim(text), paint(changeText), W); + return [one, two]; +} + +/** + * One ticker's day: name and session, price and change, the chart, the + * open, high, low and previous close, and where the numbers come from. + */ +export function detailBlock(quote, error, now, W, chartHeight, colors = PLAIN) { + const session = marketSession(quote, now); + const sessionColor = session === "open" || session === "24h" ? colors.up : session === "closed" ? colors.dim : colors.warn; + const pill = sessionColor(`● ${SESSION_LABELS[session]}`); + const head = `${colors.bold(quote.symbol)} ${colors.dim(fit(quote.name === quote.symbol ? "" : quote.name, Math.max(0, W - cells(quote.symbol) - cells(pill) - 4)))}`; + const lines = [spread(head, pill, W)]; + const change = quote.changePercent; + lines.push(`${colors.bold(formatPrice(quote))} ${tone(colors, change)(formatChange(change))}`); + lines.push(""); + lines.push(...paintChart(chartRows(quote.series, quote.previousClose, W, chartHeight), colors, change)); + const pair = isCryptoPair(quote.symbol); + const labels = pair ? ["24h open", "24h high", "24h low", "24h ago"] : ["Open", "High", "Low", "Prev close"]; + const values = [quote.open, quote.high, quote.low, quote.previousClose] + .map((value) => (typeof value === "number" ? formatPrice({ ...quote, price: value, currency: null }) : "—")); + const column = Math.floor(W / 4); + lines.push(labels.map((label) => padEnd(colors.dim(fit(label, column - 1)), column)).join("").trimEnd()); + lines.push(values.map((value) => padEnd(colors.bold(fit(value, column - 1)), column)).join("").trimEnd()); + const stale = formatStaleDate(quote.timestamp, now); + const parts = [`As of ${stale ? `${stale} ` : ""}${formatTime(quote.timestamp)}`, delayText(quote), pair ? "Binance Spot · 24h" : "Yahoo Finance"] + .filter(Boolean); + // "regular session" only when it fits; the rest is never cut. + const full = [...parts, ...(pair ? [] : ["regular session"])].join(" · "); + lines.push(colors.dim(fit(cells(full) <= W ? full : parts.join(" · "), W))); + if (error) lines.push(colors.warn(fit(`Cached quote · ${error}`, W))); + return lines; +} + +/** The detail layer: the day of one ticker, filling the layer. */ +export function detailScreen(quote, error, now, width, height, colors = PLAIN) { + const W = Math.max(30, width - 4); + const fixed = 10 + (error ? 1 : 0); + const chartHeight = Math.max(3, Math.min(16, height - fixed - 2)); + const block = detailBlock(quote, error, now, W, chartHeight, colors); + const card = `${colors.link(PULSE_URLS.detail, `${colors.brandBold("Pulse for Mac")} ${colors.dim(fit("Menu bar quotes, charts and positions", Math.max(0, W - 34)))} ${colors.brand("pulseticker.app ↗")}`)}`; + const lines = ["", ...block, colors.dim("─".repeat(W)), card, colors.dim("Esc closes")]; + return lines.slice(0, height).map((line) => clip(` ${line}`, width)); +} + +/** The band: one line of quotes, for a pane BAND_ROWS tall or less. */ +export function band(state, width, colors = PLAIN) { + const parts = [colors.brandBold("◆ Pulse")]; + if (state.paused) parts.push(colors.warn("Paused")); + if (!state.symbols.length) parts.push(colors.dim("Make the pane taller to add tickers.")); + for (const symbol of state.symbols) { + const quote = state.quotes[symbol]; + if (!quote) { parts.push(`${colors.bold(symbol)} ${colors.dim("—")}`); continue; } + const cached = state.errors[symbol] ? ` ${colors.dim("cached")}` : ""; + parts.push(`${colors.bold(symbol)} ${formatBandPrice(quote)} ${tone(colors, quote.changePercent)(formatChange(quote.changePercent))}${cached}`); + } + let line = " "; + for (const part of parts) { + const next = line === " " ? ` ${part}` : `${line} ${part}`; + if (cells(next) > width) break; + line = next; + } + return line; +} diff --git a/rex/src/install.js b/rex/src/install.js new file mode 100644 index 0000000..219a267 --- /dev/null +++ b/rex/src/install.js @@ -0,0 +1,125 @@ +// Adds Pulse to Rex's command palette: a marked block at the end of Rex's +// init.lua that loads lua/pulse.lua from this package. Nothing else in the +// file is touched, and the block is checked with `rex config check` before it +// stays; a failed check puts the file back as it was. +import { spawnSync } from "node:child_process"; +import { accessSync, constants, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { delimiter, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const BEGIN = "-- >>> pulse >>>"; +export const END = "-- <<< pulse <<<"; + +/** Rex's own rule: REX_CONFIG, else rex/init.lua in the account's config directory. */ +export function configPath(env = process.env) { + if (env.REX_CONFIG) return env.REX_CONFIG; + const config = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"); + return join(config, "rex", "init.lua"); +} + +const luaString = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`; + +/** The managed block: which Lua file to load and which program the actions run. */ +export function loaderBlock(luaPath, command) { + return [ + BEGIN, + "-- Managed by `pulse-rex install`; `pulse-rex uninstall` removes it.", + `dofile(${luaString(luaPath)}).setup({ bin = { ${command.map(luaString).join(", ")} } })`, + END, + "", + ].join("\n"); +} + +/** `content` with the managed block replaced, or added at the end; `null` removes it. */ +export function withBlock(content, block) { + const start = content.indexOf(BEGIN); + const endAt = start === -1 ? -1 : content.indexOf(END, start); + if (start !== -1 && endAt !== -1) { + let after = content.slice(endAt + END.length); + if (after.startsWith("\n")) after = after.slice(1); + let before = content.slice(0, start); + if (!block) before = before.replace(/\n\n$/, "\n"); + return before + (block ?? "") + after; + } + if (!block) return content; + if (!content.trim()) return block; + return `${content.replace(/\n*$/, "")}\n\n${block}`; +} + +function rex(args) { + const result = spawnSync("rex", args, { encoding: "utf8", timeout: 20_000 }); + if (result.error) return { ok: false, text: `could not run rex (${result.error.message}). Is Rex's CLI on your PATH?` }; + return { ok: result.status === 0, text: (result.stderr || result.stdout || "").trim() }; +} + +function read(path) { + try { return readFileSync(path, "utf8"); } catch { return null; } +} + +const real = (path) => { try { return realpathSync(path); } catch { return null; } }; + +/** + * The node and the package to write into init.lua. Node reports its real + * path, which names its version under a version manager (…/node-v22.23.4/…) + * and breaks when node is upgraded. So prefer a `node` on PATH that is the + * same program through a stable link (…/node/current/bin/node), and the + * package under that node's prefix when it is the same package. + */ +export function stablePaths(env = process.env, execPath = process.execPath, root = packageRoot()) { + const realNode = real(execPath) ?? execPath; + let node = execPath; + for (const dir of (env.PATH ?? "").split(delimiter).filter(Boolean)) { + const candidate = join(dir, "node"); + try { accessSync(candidate, constants.X_OK); } catch { continue; } + if (real(candidate) === realNode) { node = candidate; break; } + } + let pkg = root; + const linked = join(dirname(dirname(node)), "lib", "node_modules", "rex-pulse-ticker"); + if (linked !== root && real(linked) === real(root)) pkg = linked; + return { node, lua: join(pkg, "lua", "pulse.lua"), bin: join(pkg, "bin", "pulse-rex.js") }; +} + +function packageRoot() { + return dirname(dirname(realpathSync(fileURLToPath(import.meta.url)))); +} + +function apply(next, previous, config) { + mkdirSync(dirname(config), { recursive: true }); + writeFileSync(config, next); + const check = rex(["config", "check", config]); + if (!check.ok) { + if (previous === null) writeFileSync(config, ""); else writeFileSync(config, previous); + throw new Error(`rex config check failed, so ${config} was put back as it was:\n${check.text}`); + } + return rex(["config", "reload"]).ok; +} + +export function install() { + const config = configPath(); + const files = stablePaths(); + const previous = read(config); + const next = withBlock(previous ?? "", loaderBlock(files.lua, [files.node, files.bin])); + if (next === previous) { + return `Pulse is already in ${config}. Press cmd+shift+p in Rex and type Pulse.`; + } + const reloaded = apply(next, previous, config); + return [ + `Added Pulse to ${config}${reloaded ? "" : " (rex config reload didn't run; reload Rex's config yourself)"}.`, + "In Rex, press cmd+shift+p and type Pulse:", + " Pulse: Open Watchlist the watchlist beside the focused pane", + " Pulse: Add Ticker… add AAPL, 0700.HK, ^GSPC or BTC/USDT", + " Pulse: Refresh Quotes one round now", + " Pulse: Pause or Resume stop or restart automatic refresh", + "To bind a key, add to init.lua after the Pulse block:", + ' rex.bind("cmd+shift+u", "pulse_open")', + ].join("\n"); +} + +export function uninstall() { + const config = configPath(); + const previous = read(config); + if (previous === null || !previous.includes(BEGIN)) return `Pulse isn't in ${config}. Nothing to remove.`; + apply(withBlock(previous, null), previous, config); + return `Removed Pulse from ${config}. Your watchlist is kept; delete ~/.config/pulse-rex to remove it too.`; +} diff --git a/rex/src/quotes.js b/rex/src/quotes.js new file mode 100644 index 0000000..99d74a0 --- /dev/null +++ b/rex/src/quotes.js @@ -0,0 +1,248 @@ +// Symbols, the two quote sources and number formatting. No Rex imports, so +// tests run it under Node. Shared with the Herdr mod (herdr/pulse/mods/pulse/quotes.js): +// only this header and PULSE_URLS differ. + +// The only two hosts Pulse contacts. +export const YAHOO_CHART = "https://query1.finance.yahoo.com/v8/finance/chart/"; +export const BINANCE_TICKERS = "https://data-api.binance.vision/api/v3/ticker/24hr"; +export const BINANCE_KLINES = "https://data-api.binance.vision/api/v3/klines"; +// The one page Pulse for Rex links to (a terminal hyperlink the person clicks), tagged +// with where the click came from. +export const PULSE_URLS = { + panel: "https://www.pulseticker.app/?utm_source=rex&utm_medium=plugin&utm_content=sidebar", + detail: "https://www.pulseticker.app/?utm_source=rex&utm_medium=plugin&utm_content=detail", +}; +// Shown until the person saves a watchlist of their own. +export const STARTER_SYMBOLS = ["AAPL", "NVDA", "^GSPC", "BTC/USDT"]; +export const BINANCE_BATCH = 100; + +export class QuoteError extends Error { + constructor(message, options = {}) { + super(message); + this.retryAfterMs = options.retryAfterMs; + this.invalidSymbol = options.invalidSymbol === true; + } +} + +/** A Binance Spot pair is written BASE/QUOTE (BTC/USDT); a dash stays a Yahoo symbol (BTC-USD). */ +export function isCryptoPair(symbol) { + return /^[A-Z0-9]{1,20}\/[A-Z0-9]{1,20}$/.test(symbol); +} + +/** Yahoo tickers or Binance pairs, never company names or URLs. Throws a message for people. */ +export function normalizeSymbol(input) { + let symbol = String(input ?? "").trim().toUpperCase(); + if (isCryptoPair(symbol)) return symbol; + if (!/^[A-Z0-9^][A-Z0-9.^=\-]{0,31}$/.test(symbol)) { + throw new QuoteError("Enter a ticker, such as AAPL, 0700.HK or ^GSPC, or a pair, such as BTC/USDT."); + } + if (/^\d{6}\.SH$/.test(symbol)) symbol = symbol.replace(/\.SH$/, ".SS"); + const hk = /^(\d{1,5})\.HK$/.exec(symbol); + if (hk) symbol = String(Number(hk[1])).padStart(4, "0") + ".HK"; + return symbol; +} + +const positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0; + +const cleanText = (value) => typeof value === "string" + ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, 100) || null + : null; + +/** Today's 5-minute bars: the quote metadata and the intraday line in one request. */ +export function yahooUrl(symbol) { + return YAHOO_CHART + encodeURIComponent(normalizeSymbol(symbol)) + "?interval=5m&range=1d&includePrePost=false"; +} + +const finite = (value) => typeof value === "number" && Number.isFinite(value); +const MAX_POINTS = 400; + +/** Finite closes in order; gaps (null bars) are dropped. */ +function cleanSeries(values) { + if (!Array.isArray(values)) return []; + const series = values.filter((value) => positive(value)); + return series.length > MAX_POINTS ? series.slice(series.length - MAX_POINTS) : series; +} + +const period = (value) => finite(value?.start) && finite(value?.end) && value.end > value.start + ? [value.start * 1000, value.end * 1000] : null; + +/** `response` is `{ status, ok, text }` with the body already read. */ +export function decodeYahoo(symbol, response, now) { + // Herdr's fetch does not expose headers, so Retry-After is unknown: wait at least a minute. + if (response.status === 429) throw new QuoteError("Yahoo rate limited requests.", { retryAfterMs: 60_000 }); + if (response.status === 404) throw new QuoteError("Ticker not found on Yahoo Finance."); + if (!response.ok) throw new QuoteError(`Yahoo returned HTTP ${response.status}.`); + let body; + try { body = JSON.parse(response.text); } catch { throw new QuoteError("Yahoo returned an unreadable response."); } + const meta = body?.chart?.result?.[0]?.meta; + if (body?.chart?.error || !meta) throw new QuoteError("No quote available for this ticker."); + // Never show another instrument's response under the requested ticker. + let returned = null; + try { returned = typeof meta.symbol === "string" ? normalizeSymbol(meta.symbol) : null; } catch { /* checked below */ } + if (returned !== symbol) throw new QuoteError("Yahoo returned a different ticker."); + if (!positive(meta.regularMarketPrice) || !positive(meta.regularMarketTime)) { + throw new QuoteError("Yahoo returned an incomplete quote."); + } + const close = positive(meta.previousClose) ? meta.previousClose : meta.chartPreviousClose; + const delay = meta.exchangeDataDelayedBy; + const bars = body.chart.result[0].indicators?.quote?.[0] ?? {}; + const series = cleanSeries(bars.close); + const opens = cleanSeries(bars.open); + const highs = cleanSeries(bars.high); + const lows = cleanSeries(bars.low); + const periods = meta.currentTradingPeriod ?? {}; + return { + symbol, + name: cleanText(meta.longName) ?? cleanText(meta.shortName) ?? symbol, + price: meta.regularMarketPrice, + changePercent: positive(close) ? (meta.regularMarketPrice - close) / close * 100 : null, + currency: typeof meta.currency === "string" && /^[A-Z]{3}$/.test(meta.currency) ? meta.currency : null, + timestamp: meta.regularMarketTime * 1000, + fetchedAt: now, + delaySeconds: typeof delay === "number" && Number.isFinite(delay) && delay >= 0 ? delay : null, + series, + open: opens[0] ?? null, + high: positive(meta.regularMarketDayHigh) ? meta.regularMarketDayHigh : highs.length ? Math.max(...highs) : null, + low: positive(meta.regularMarketDayLow) ? meta.regularMarketDayLow : lows.length ? Math.min(...lows) : null, + previousClose: positive(close) ? close : null, + periods: { pre: period(periods.pre), regular: period(periods.regular), post: period(periods.post) }, + }; +} + +/** One request for up to BINANCE_BATCH pairs: `?symbols=["BTCUSDT","ETHUSDT"]`. */ +export function binanceUrl(pairs) { + return `${BINANCE_TICKERS}?symbols=${encodeURIComponent(JSON.stringify(pairs.map((pair) => pair.replace("/", ""))))}`; +} + +/** Quotes by requested pair; a pair Binance did not return is absent. */ +export function decodeBinance(pairs, response, now) { + // -1121 Invalid symbol: one unknown or delisted pair fails the whole batch. + if (response.status === 400) throw new QuoteError("Binance has no Spot pair with this name.", { invalidSymbol: true }); + if (response.status === 429 || response.status === 418) throw new QuoteError("Binance rate limited requests."); + if (!response.ok) throw new QuoteError(`Binance returned HTTP ${response.status}.`); + let body; + try { body = JSON.parse(response.text); } catch { throw new QuoteError("Binance returned an unreadable response."); } + const wanted = new Map(pairs.map((pair) => [pair.replace("/", ""), pair])); + const quotes = {}; + for (const ticker of Array.isArray(body) ? body : [body]) { + const pair = typeof ticker?.symbol === "string" ? wanted.get(ticker.symbol) : undefined; + if (!pair) continue; + const price = Number(ticker.lastPrice); + const close = Number(ticker.prevClosePrice); + const time = Number(ticker.closeTime); + if (!positive(price) || !positive(time)) continue; + quotes[pair] = { + symbol: pair, + name: "Binance Spot", + price, + // Against the price 24 hours before the last trade. + changePercent: positive(close) ? (price - close) / close * 100 : null, + currency: pair.split("/")[1], + timestamp: time, + fetchedAt: now, + delaySeconds: 0, + series: [], + open: positive(Number(ticker.openPrice)) ? Number(ticker.openPrice) : null, + high: positive(Number(ticker.highPrice)) ? Number(ticker.highPrice) : null, + low: positive(Number(ticker.lowPrice)) ? Number(ticker.lowPrice) : null, + previousClose: positive(close) ? close : null, + periods: null, + }; + } + return quotes; +} + +/** The last 24 hours of one pair in 15-minute bars. */ +export function binanceKlinesUrl(pair) { + return `${BINANCE_KLINES}?symbol=${encodeURIComponent(pair.replace("/", ""))}&interval=15m&limit=96`; +} + +/** Closing prices, oldest first; throws when Binance answers with anything else. */ +export function decodeKlines(response) { + if (!response.ok) throw new QuoteError(`Binance returned HTTP ${response.status}.`); + let body; + try { body = JSON.parse(response.text); } catch { throw new QuoteError("Binance returned an unreadable response."); } + if (!Array.isArray(body)) throw new QuoteError("Binance returned an unreadable response."); + return cleanSeries(body.map((bar) => Array.isArray(bar) ? Number(bar[4]) : NaN)); +} + +/** Where a stock's market is now: "pre", "open", "post" or "closed"; a pair trades around the clock. */ +export function marketSession(quote, now) { + if (!quote.periods) return "24h"; + const within = (range) => range && now >= range[0] && now < range[1]; + if (within(quote.periods.regular)) return "open"; + if (within(quote.periods.pre)) return "pre"; + if (within(quote.periods.post)) return "post"; + return "closed"; +} + +export const SESSION_LABELS = { + open: "Market open", pre: "Pre-market", post: "After hours", closed: "Market closed", "24h": "Trades 24h", +}; + +/** + * The line through `series`, scaled into its box as [x%, y%] points, and where + * the reference price (the previous close) falls, or null when it is outside. + * Fewer than two points draw nothing. + */ +export function chartGeometry(series, reference) { + if (!Array.isArray(series) || series.length < 2) return null; + const values = positive(reference) ? [...series, reference] : series; + let min = Math.min(...values); + let max = Math.max(...values); + if (max - min < max * 1e-9) { min -= 1; max += 1; } + // 8% headroom keeps the stroke inside the box. + const pad = (max - min) * 0.08; + min -= pad; max += pad; + const y = (value) => Math.round((1 - (value - min) / (max - min)) * 10000) / 100; + const last = series.length - 1; + return { + points: series.map((value, index) => [Math.round(index / last * 10000) / 100, y(value)]), + reference: positive(reference) ? y(reference) : null, + }; +} + +// Herdr's QuickJS runtime has no Intl, so numbers and dates are formatted by hand. +const group = (digits) => digits.replace(/\B(?=(\d{3})+(?!\d))/g, ","); + +function significant(price) { + // Below 1, keep 2 to 4 significant digits: 0.00000441 must not round to 0.000004. + const places = Math.min(20, 3 - Math.floor(Math.log10(price))); + let text = price.toFixed(places); + const count = (s) => s.replace(".", "").replace(/^0+/, "").length; + while (text.endsWith("0") && count(text) > 2) text = text.slice(0, -1); + return text; +} + +export function formatPrice(quote) { + const [whole, fraction] = (quote.price < 1 ? significant(quote.price) : quote.price.toFixed(2)).split("."); + const price = group(whole) + (fraction === undefined ? "" : "." + fraction); + return quote.currency ? `${price} ${quote.currency}` : price; +} + +/** The compact band leaves out USD and a pair's own quote currency. */ +export function formatBandPrice(quote) { + const named = quote.currency === "USD" || quote.symbol.endsWith(`/${quote.currency}`); + return formatPrice(named ? { ...quote, currency: null } : quote); +} + +export function formatChange(value) { + return value === null || value === undefined ? "—" : `${value >= 0 ? "+" : ""}${value.toFixed(2)}%`; +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** A quote from an earlier local day gets its date, so a closed market never reads as today's. */ +export function formatStaleDate(timestamp, now) { + const quoted = new Date(timestamp); + const today = new Date(now); + if (quoted.getFullYear() === today.getFullYear() && quoted.getMonth() === today.getMonth() + && quoted.getDate() === today.getDate()) return ""; + return `${MONTHS[quoted.getMonth()]} ${quoted.getDate()}`; +} + +/** Local wall-clock time, 24-hour: "15:04". */ +export function formatTime(timestamp) { + const date = new Date(timestamp); + return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; +} diff --git a/rex/src/store.js b/rex/src/store.js new file mode 100644 index 0000000..0a6a3d3 --- /dev/null +++ b/rex/src/store.js @@ -0,0 +1,52 @@ +// Where Pulse for Rex keeps the watchlist: one JSON file, shared by every +// Pulse pane and by the `pulse-rex` commands that Rex's palette runs. A second +// file is only touched, to ask running panes for a refresh. +import { mkdirSync, readFileSync, renameSync, statSync, unwatchFile, watchFile, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +export function storeDir(env = process.env) { + if (env.PULSE_REX_HOME) return env.PULSE_REX_HOME; + const config = env.XDG_CONFIG_HOME || join(env.HOME || homedir(), ".config"); + return join(config, "pulse-rex"); +} + +export function createStore(dir = storeDir()) { + const file = join(dir, "watchlist.json"); + const refresh = join(dir, "refresh"); + const watched = []; + return { + file, + /** The saved preferences, or undefined before the first edit (the starter list then applies). */ + load() { + try { return JSON.parse(readFileSync(file, "utf8")); } catch { return undefined; } + }, + save(preferences) { + mkdirSync(dir, { recursive: true }); + // Written whole and renamed, so a pane never reads half a file. + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, JSON.stringify(preferences, null, 2) + "\n"); + renameSync(temporary, file); + }, + requestRefresh() { + mkdirSync(dir, { recursive: true }); + writeFileSync(refresh, String(Date.now())); + }, + /** Calls `onEdit` when another process saves, `onRefresh` when one asks for a refresh. */ + watch(onEdit, onRefresh) { + const poll = { interval: 700, persistent: false }; + const changed = (callback) => (current, previous) => { + if (current.mtimeMs !== previous.mtimeMs) callback(); + }; + watchFile(file, poll, changed(onEdit)); + watchFile(refresh, poll, changed(onRefresh)); + watched.push(file, refresh); + }, + close() { + for (const path of watched.splice(0)) unwatchFile(path); + }, + exists() { + try { return statSync(file).isFile(); } catch { return false; } + }, + }; +} diff --git a/rex/src/tui.js b/rex/src/tui.js new file mode 100644 index 0000000..17de8e4 --- /dev/null +++ b/rex/src/tui.js @@ -0,0 +1,357 @@ +// The programs Rex runs in a pane: the watchlist, the detail layer, and the +// add prompt. Everything they print comes from format.js. +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { QuoteError } from "./quotes.js"; +import { Watchlist } from "./watchlist.js"; +import { createStore } from "./store.js"; +import { detailScreen, fit, pane, palette, wrap } from "./format.js"; + +export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version; +const HEADERS = { "User-Agent": `Pulse-Rex/${VERSION}`, Accept: "application/json" }; +// Points sent along to the detail layer; plenty for a chart a terminal wide. +const DETAIL_POINTS = 160; + +// --------------------------------------------------------------------------- +// The terminal + +const out = (text) => process.stdout.write(text); + +function screen() { + const { stdin, stdout } = process; + let open = false; + const api = { + get width() { return stdout.columns || 48; }, + get height() { return stdout.rows || 24; }, + start(mouse) { + open = true; + out("\x1b[?1049h\x1b[?25l" + (mouse ? "\x1b[?1000h\x1b[?1006h" : "")); + if (stdin.isTTY) stdin.setRawMode(true); + stdin.resume(); + }, + draw(lines) { + out("\x1b[H" + lines.map((line) => line + "\x1b[K").join("\r\n") + "\x1b[J"); + }, + stop() { + if (!open) return; + open = false; + out("\x1b[?1000l\x1b[?1006l\x1b[?25h\x1b[?1049l"); + if (stdin.isTTY) stdin.setRawMode(false); + stdin.pause(); + }, + }; + return api; +} + +/** Asks the terminal for its background (OSC 11), to pick Pulse's blue for it. Dark when it doesn't say. */ +function detectDark(timeoutMs = 150) { + const { stdin } = process; + if (!stdin.isTTY) return Promise.resolve(true); + return new Promise((resolve) => { + let reply = ""; + const done = (dark) => { clearTimeout(timer); stdin.off("data", listen); resolve(dark); }; + const listen = (data) => { + reply += data.toString(); + const match = /\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(reply); + if (!match) return; + const [r, g, b] = match.slice(1).map((hex) => parseInt(hex, 16) / (16 ** hex.length - 1)); + done(0.2126 * r + 0.7152 * g + 0.0722 * b < 0.5); + }; + const timer = setTimeout(() => done(true), timeoutMs); + stdin.setRawMode(true); + stdin.resume(); + stdin.on("data", listen); + out("\x1b]11;?\x1b\\"); + }); +} + +/** Splits raw input into keys: named ones, printable text, and clicks. */ +export function keys(data) { + const found = []; + let rest = data; + const named = [ + ["\x1b[A", "up"], ["\x1bOA", "up"], ["\x1b[B", "down"], ["\x1bOB", "down"], + ["\x1b[5~", "pageup"], ["\x1b[6~", "pagedown"], ["\x1b[3~", "delete"], + ["\r", "enter"], ["\n", "enter"], ["\x7f", "backspace"], ["\b", "backspace"], ["\x03", "interrupt"], + ]; + while (rest.length) { + const click = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])/.exec(rest); + if (click) { + if (click[4] === "M" && Number(click[1]) === 0) found.push({ name: "click", x: Number(click[2]), y: Number(click[3]) }); + if (click[4] === "M" && Number(click[1]) === 64) found.push({ name: "up" }); + if (click[4] === "M" && Number(click[1]) === 65) found.push({ name: "down" }); + rest = rest.slice(click[0].length); + continue; + } + const hit = named.find(([sequence]) => rest.startsWith(sequence)); + if (hit) { found.push({ name: hit[1] }); rest = rest.slice(hit[0].length); continue; } + if (rest[0] === "\x1b") { + // A sequence we don't use (or a reply to a query): skip it whole. A lone Esc is Escape. + const other = /^\x1b(\[[0-9;?<>]*[ -\/]*[@-~]|\][^\x07\x1b]*(\x07|\x1b\\)|O.)/.exec(rest); + if (other) { rest = rest.slice(other[0].length); continue; } + found.push({ name: "escape" }); + rest = rest.slice(1); + continue; + } + const char = String.fromCodePoint(rest.codePointAt(0)); + if (char >= " ") found.push({ name: "text", text: char }); + rest = rest.slice(char.length); + } + return found; +} + +function host(store) { + return { + load: () => store.load(), + save: (preferences) => store.save(preferences), + fetch: (url) => fetch(url, { headers: HEADERS, signal: AbortSignal.timeout(15_000) }), + now: () => Date.now(), + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + changed: () => {}, + }; +} + +/** Opens one ticker's day in a Rex floating layer; false when this isn't a Rex pane or it failed. */ +function openLayer(quote, bin) { + const session = process.env.REX_SESSION; + if (!session) return false; + const step = Math.max(1, Math.ceil(quote.series.length / DETAIL_POINTS)); + const sent = { ...quote, series: quote.series.filter((_, i) => i % step === 0 || i === quote.series.length - 1) }; + const request = { + session_id: session, + bounds: [0.18, 0.12, 0.64, 0.66], + focus: true, + layout: { block: { + flavor: "com.superlogical.terminal.shell", + label: `Pulse · ${quote.symbol}`, + options: { command: [...bin, "detail", "--quote", JSON.stringify(sent)] }, + } }, + }; + const result = spawnSync("rex", ["api", "call", "-s", session, "session.new_layer", "-"], { + input: JSON.stringify(request), encoding: "utf8", timeout: 10_000, + }); + return result.status === 0; +} + +/** + * Moves the border between this pane and the one it was opened beside, so + * Pulse gets the width it was opened for. The Rex app evens out a new split + * once it shows it, so this runs after a moment, and once more in case the + * app was slow. + */ +function fitWidth(fit) { + const session = process.env.REX_SESSION; + const self = process.env.REX_BLOCK; + if (!fit || !session || !self) return; + const resize = () => spawnSync("rex", ["api", "call", "-s", session, "session.resize_pane", "-"], { + input: JSON.stringify({ direction: "horizontal", before_block_id: fit.beside, after_block_id: self, ratio: fit.ratio }), + encoding: "utf8", timeout: 5_000, + }); + setTimeout(resize, 400).unref(); + setTimeout(resize, 1500).unref(); +} + +// --------------------------------------------------------------------------- +// The watchlist pane + +export async function runPane(bin, fit = null) { + const store = createStore(); + const term = screen(); + const colors = palette(await detectDark()); + const watch = new Watchlist(host(store)); + const ui = { selected: 0, adding: false, input: "", notice: "", error: "", inline: null, rows: {} }; + let scheduled = false; + + const state = () => ({ + symbols: watch.preferences.symbols, + quotes: watch.quotes, + errors: watch.errors, + paused: watch.preferences.paused, + loading: watch.loading, + message: watch.message, + selected: ui.selected, + adding: ui.adding, + input: ui.input, + notice: ui.notice, + error: ui.error, + now: Date.now(), + }); + + const draw = () => { + scheduled = false; + const count = watch.preferences.symbols.length; + ui.selected = Math.max(0, Math.min(ui.selected, count - 1)); + if (ui.inline) { + const quote = watch.quotes[ui.inline]; + if (!quote) ui.inline = null; + else { term.draw(detailScreen(quote, watch.errors[ui.inline], Date.now(), term.width, term.height, colors)); return; } + } + const drawn = pane(state(), term.width, term.height, colors); + ui.rows = drawn.rows; + term.draw(drawn.lines); + }; + const redraw = () => { + if (scheduled) return; + scheduled = true; + setImmediate(draw); + }; + watch.host.changed = redraw; + + const quit = () => { + watch.stop(); + store.close(); + term.stop(); + process.exit(0); + }; + + const say = (run) => { + ui.error = ""; + try { ui.notice = run(); } catch (error) { + ui.notice = ""; + ui.error = error instanceof QuoteError ? error.message : String(error?.message ?? error); + } + }; + + const open = () => { + const symbol = watch.preferences.symbols[ui.selected]; + const quote = symbol && watch.quotes[symbol]; + if (!quote) { ui.notice = symbol ? `${symbol} has no quote yet.` : ""; return; } + if (!openLayer(quote, bin)) ui.inline = symbol; + }; + + const onKey = (key) => { + if (key.name === "interrupt") return quit(); + if (ui.inline) { + if (["escape", "enter", "interrupt"].includes(key.name) || key.text === "q") ui.inline = null; + return; + } + if (ui.adding) { + if (key.name === "escape") { ui.adding = false; ui.input = ""; ui.error = ""; } + else if (key.name === "enter") { + const typed = ui.input.trim(); + if (!typed) { ui.adding = false; return; } + say(() => watch.add(typed)); + if (!ui.error) { + ui.adding = false; + ui.input = ""; + ui.selected = watch.preferences.symbols.length - 1; + } + } else if (key.name === "backspace") ui.input = [...ui.input].slice(0, -1).join(""); + else if (key.name === "text" && ui.input.length < 40) ui.input += key.text; + return; + } + const count = watch.preferences.symbols.length; + ui.error = ""; + switch (key.name) { + case "up": ui.selected = (ui.selected + count - 1) % Math.max(1, count); return; + case "down": ui.selected = (ui.selected + 1) % Math.max(1, count); return; + case "pageup": ui.selected = 0; return; + case "pagedown": ui.selected = count - 1; return; + case "enter": open(); return; + case "delete": case "backspace": remove(); return; + case "escape": ui.notice = ""; return; + case "click": { + const index = ui.rows[key.y - 1]; + if (index === undefined) return; + if (index === ui.selected) open(); else ui.selected = index; + return; + } + default: break; + } + if (key.name !== "text") return; + switch (key.text) { + case "q": quit(); return; + case "k": onKey({ name: "up" }); return; + case "j": onKey({ name: "down" }); return; + case "a": case "+": ui.adding = true; ui.input = ""; ui.notice = ""; return; + case "x": case "-": remove(); return; + case "r": watch.refreshNow(); ui.notice = "Refreshing now."; return; + case "p": say(() => watch.pause(!watch.preferences.paused)); return; + default: break; + } + }; + const remove = () => { + const symbol = watch.preferences.symbols[ui.selected]; + if (symbol) say(() => watch.remove(symbol)); + }; + + term.start(true); + fitWidth(fit); + process.stdin.on("data", (data) => { + for (const key of keys(data.toString())) onKey(key); + draw(); + }); + process.stdout.on("resize", draw); + process.on("SIGHUP", quit); + process.on("SIGTERM", quit); + store.watch(() => { if (watch.sync()) redraw(); }, () => watch.refreshNow()); + // Market sessions and "As of" dates move with the clock, between rounds too. + setInterval(redraw, 30_000).unref(); + draw(); + await watch.run(); +} + +// --------------------------------------------------------------------------- +// The detail layer: the quote it was given, as it was. It fetches nothing. + +export async function runDetail(json) { + let quote; + try { quote = JSON.parse(json); } catch { quote = null; } + if (!quote?.symbol) { + process.stderr.write("pulse-rex detail: expected --quote with a quote from the Pulse pane.\n"); + process.exit(2); + } + const term = screen(); + const colors = palette(await detectDark()); + const draw = () => term.draw(detailScreen(quote, null, Date.now(), term.width, term.height, colors)); + const quit = () => { term.stop(); process.exit(0); }; + term.start(false); + process.stdin.on("data", (data) => { + if (keys(data.toString()).some((key) => ["escape", "enter", "interrupt"].includes(key.name) || key.text === "q")) quit(); + }); + process.stdout.on("resize", draw); + process.on("SIGHUP", quit); + draw(); +} + +// --------------------------------------------------------------------------- +// The add prompt, for the palette's "Pulse: Add Ticker…" + +export async function runPrompt() { + const store = createStore(); + const watch = new Watchlist(host(store)); + const term = screen(); + const colors = palette(await detectDark()); + let input = ""; + let error = ""; + const draw = () => { + const W = Math.max(20, term.width - 4); + term.draw([ + "", + ` ${colors.brandBold("◆ Pulse")} ${colors.dim("Add a ticker")}`, + "", + ` ${colors.brand("›")} ${input}${colors.brand("▏")}`, + "", + ...(error ? wrap(error, W).map((line) => ` ${colors.down(line)}`) : [` ${colors.dim(fit("AAPL, 0700.HK, ^GSPC, BTC/USDT", W))}`]), + ` ${colors.dim("Enter adds · Esc cancels")}`, + ]); + }; + const quit = () => { term.stop(); process.exit(0); }; + term.start(false); + process.stdin.on("data", (data) => { + for (const key of keys(data.toString())) { + if (key.name === "escape" || key.name === "interrupt") return quit(); + if (key.name === "enter") { + if (!input.trim()) return quit(); + try { watch.add(input.trim()); return quit(); } catch (cause) { + error = cause instanceof QuoteError ? cause.message : String(cause?.message ?? cause); + } + } else if (key.name === "backspace") input = [...input].slice(0, -1).join(""); + else if (key.name === "text" && input.length < 40) { input += key.text; error = ""; } + } + draw(); + }); + process.stdout.on("resize", draw); + process.on("SIGHUP", quit); + draw(); +} diff --git a/rex/src/watchlist.js b/rex/src/watchlist.js new file mode 100644 index 0000000..40dbc3d --- /dev/null +++ b/rex/src/watchlist.js @@ -0,0 +1,248 @@ +// The watchlist and its refresh loop. The host's APIs come in through `host`, +// so tests drive it under Node with a fake clock and network. Same file as the +// Herdr mod's (herdr/pulse/mods/pulse/watchlist.js) apart from this header. +import { + BINANCE_BATCH, QuoteError, STARTER_SYMBOLS, binanceKlinesUrl, binanceUrl, decodeBinance, decodeKlines, decodeYahoo, + isCryptoPair, normalizeSymbol, yahooUrl, +} from "./quotes.js"; + +export const INTERVAL_MS = 60_000; +// Stock requests are spaced at least this far apart. +export const YAHOO_SPACING_MS = 1_000; + +export function readPreferences(value) { + // Nothing saved yet: a starter list, until the first edit saves the person's own. + if (value === undefined || value === null) return { version: 1, symbols: [...STARTER_SYMBOLS], paused: false }; + const saved = typeof value === "object" ? value : null; + const symbols = []; + if (saved?.version === 1 && Array.isArray(saved.symbols)) { + for (const raw of saved.symbols) { + if (typeof raw !== "string") continue; + try { + const symbol = normalizeSymbol(raw); + if (!symbols.includes(symbol)) symbols.push(symbol); + } catch { /* Skip one bad entry, not the whole list. */ } + } + } + return { version: 1, symbols, paused: saved?.version === 1 && saved.paused === true }; +} + +/** + * host: { + * load(): unknown, save(preferences): void // the saved watchlist + * fetch(url): Promise<{ status, ok, text }> // GET, body read + * now(): number, sleep(ms): Promise + * changed(): void // redraw, from the loop only + * } + */ +export class Watchlist { + constructor(host, intervalMs = INTERVAL_MS) { + this.host = host; + this.intervalMs = intervalMs; + this.preferences = readPreferences(host.load()); + this.quotes = {}; + this.errors = {}; + this.message = ""; + this.loading = false; + this.retryAt = 0; + this.rateFailures = 0; + this.revision = 0; + this.stopped = false; + this.manual = false; + this.dirty = true; + this.lastYahooAt = -Infinity; + this.wake = null; + } + + // Edits are synchronous (the store is Herdr's shared state) and return a short notice. + edit(change) { + const preferences = readPreferences(this.host.load()); + const message = change(preferences); + this.host.save(preferences); + this.adopt(preferences); + this.revision++; + this.dirty = true; + this.poke(); + return message; + } + + add(input) { + const symbol = normalizeSymbol(input); + return this.edit((p) => { + if (p.symbols.includes(symbol)) return `${symbol} is already on your watchlist.`; + p.symbols.push(symbol); + return `Added ${symbol}.`; + }); + } + + remove(symbol) { + return this.edit((p) => { + if (!p.symbols.includes(symbol)) return `${symbol} is not on your watchlist.`; + p.symbols = p.symbols.filter((s) => s !== symbol); + return `Removed ${symbol}.`; + }); + } + + pause(paused) { + return this.edit((p) => { + p.paused = paused; + return paused ? "Automatic refresh paused." : "Automatic refresh resumed."; + }); + } + + /** One round now, also while paused; a Yahoo cooldown still holds for stocks. */ + refreshNow() { + this.manual = true; + this.poke(); + } + + stop() { + this.stopped = true; + this.revision++; + this.poke(); + } + + poke() { + const wake = this.wake; + this.wake = null; + wake?.(); + } + + /** Picks up another copy's edit of the shared list at once (the main view calls it on render). */ + sync() { + const preferences = readPreferences(this.host.load()); + if (JSON.stringify(preferences) === JSON.stringify(this.preferences)) return false; + this.adopt(preferences); + this.revision++; + this.dirty = true; + this.poke(); + return true; + } + + adopt(preferences) { + this.preferences = preferences; + const keep = new Set(preferences.symbols); + for (const record of [this.quotes, this.errors]) { + for (const key of Object.keys(record)) if (!keep.has(key)) delete record[key]; + } + } + + /** Runs until stop(). Each round starts the interval after the previous one ends. */ + async run() { + while (!this.stopped) { + const manual = this.manual; + this.manual = false; + this.dirty = false; + // Another copy may have edited the shared list. + this.adopt(readPreferences(this.host.load())); + const due = manual || (!this.preferences.paused && this.preferences.symbols.length > 0); + if (due) await this.round(manual); + if (this.stopped) return; + this.host.changed(); + if (this.manual || this.dirty) continue; + const idle = this.preferences.paused || !this.preferences.symbols.length; + await new Promise((resolve) => { + this.wake = resolve; + if (!idle) this.host.sleep(this.intervalMs).then(resolve); + }); + this.wake = null; + } + } + + async round(manual) { + const revision = this.revision; + const current = () => !this.stopped && revision === this.revision; + const symbols = this.preferences.symbols; + this.loading = true; + this.message = ""; + this.host.changed(); + try { + const pairs = symbols.filter(isCryptoPair); + for (let i = 0; i < pairs.length && current(); i += BINANCE_BATCH) { + await this.crypto(pairs.slice(i, i + BINANCE_BATCH), current); + } + const tickers = symbols.filter((s) => !isCryptoPair(s)); + if (!tickers.length || !current()) return; + if (this.host.now() < this.retryAt) { + // Pairs keep their cadence through a Yahoo cooldown; stocks wait it out. + this.message = `Yahoo rate limited requests. Retry after ${Math.ceil((this.retryAt - this.host.now()) / 1000)}s.`; + return; + } + for (const [index, symbol] of tickers.entries()) { + const wait = YAHOO_SPACING_MS - (this.host.now() - this.lastYahooAt); + if (wait > 0) await this.host.sleep(wait); + if (!current()) return; + this.lastYahooAt = this.host.now(); + try { + const response = await this.get(yahooUrl(symbol)); + if (!current()) return; + this.quotes[symbol] = decodeYahoo(symbol, response, this.host.now()); + delete this.errors[symbol]; + } catch (error) { + if (!current()) return; + this.errors[symbol] = error instanceof QuoteError ? error.message : "Could not reach Yahoo Finance."; + if (error instanceof QuoteError && error.retryAfterMs !== undefined) { + this.rateFailures++; + const backoff = Math.min(900_000, 60_000 * 2 ** Math.min(this.rateFailures - 1, 4)); + this.retryAt = this.host.now() + Math.max(backoff, error.retryAfterMs); + this.message = "Yahoo rate limited requests. Automatic retries are delayed."; + for (const rest of tickers.slice(index + 1)) this.errors[rest] = "Refresh deferred: Yahoo rate limited requests."; + return; + } + } + this.host.changed(); + } + if (current()) { this.rateFailures = 0; this.retryAt = 0; } + } finally { + this.loading = false; + } + } + + async get(url) { + const response = await this.host.fetch(url); + return { status: response.status, ok: response.ok, text: await response.text() }; + } + + /** One request per batch; an unknown pair fails the batch, so then ask pair by pair. */ + async crypto(pairs, current) { + const fetchPairs = async (list) => { + const response = await this.get(binanceUrl(list)); + if (!current()) return; + const quotes = decodeBinance(list, response, this.host.now()); + for (const pair of list) { + if (quotes[pair]) { + // Keep the last line until a new one arrives. + quotes[pair].series = this.quotes[pair]?.series ?? []; + this.quotes[pair] = quotes[pair]; + delete this.errors[pair]; + } else this.errors[pair] = "Binance returned no quote for this pair."; + } + }; + const fail = (list, error) => { + for (const pair of list) this.errors[pair] = error instanceof QuoteError ? error.message : "Could not reach Binance."; + }; + try { + await fetchPairs(pairs); + } catch (error) { + if (!current()) return; + if (error instanceof QuoteError && error.invalidSymbol && pairs.length > 1) { + for (const pair of pairs) { + if (!current()) return; + try { await fetchPairs([pair]); } catch (cause) { if (current()) fail([pair], cause); } + } + } else fail(pairs, error); + } + if (!current()) return; + this.host.changed(); + // The 24-hour line, one request a pair; a failure only leaves the line as it was. + for (const pair of pairs) { + if (!current()) return; + if (!this.quotes[pair]) continue; + try { + const series = decodeKlines(await this.get(binanceKlinesUrl(pair))); + if (current() && this.quotes[pair]) this.quotes[pair].series = series; + } catch { /* The quote itself is fine. */ } + } + if (current()) this.host.changed(); + } +} diff --git a/rex/tests/pulse.test.mjs b/rex/tests/pulse.test.mjs new file mode 100644 index 0000000..7834be7 --- /dev/null +++ b/rex/tests/pulse.test.mjs @@ -0,0 +1,195 @@ +// node --test rex/tests/*.test.mjs (src/ imports nothing from Rex; the Lua is checked with `rex config check`) +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { PULSE_URLS } from "../src/quotes.js"; +import { PLAIN, band, cells, chartRows, detailScreen, fit, pane, strip, palette, wrap } from "../src/format.js"; +import { BEGIN, END, configPath, loaderBlock, stablePaths, withBlock } from "../src/install.js"; +import { createStore } from "../src/store.js"; +import { Watchlist } from "../src/watchlist.js"; +import { keys } from "../src/tui.js"; + +const here = (path) => fileURLToPath(new URL(path, import.meta.url)); +// Everything but the header comment (and, for quotes.js, PULSE_URLS) matches the Herdr mod's copy, +// whose behavior herdr/tests covers. +const body = (path) => readFileSync(here(path), "utf8") + .replace(/^(\/\/.*\n)+/, "") + .replace(/\/\/ The one page[\s\S]*?\n};\n/, ""); + +test("quotes.js and watchlist.js match the Herdr mod's", () => { + for (const file of ["quotes.js", "watchlist.js"]) { + assert.equal(body(`../src/${file}`), body(`../../herdr/pulse/mods/pulse/${file}`), file); + } +}); + +test("links to Pulse for Mac are tagged as coming from Rex", () => { + for (const url of Object.values(PULSE_URLS)) { + const link = new URL(url); + assert.equal(link.origin, "https://www.pulseticker.app"); + assert.equal(link.searchParams.get("utm_source"), "rex"); + assert.equal(link.searchParams.get("utm_medium"), "plugin"); + } +}); + +// --------------------------------------------------------------------------- + +const NOW = Date.UTC(2026, 10, 12, 16, 0); +const quote = (symbol, price, previousClose, extra = {}) => ({ + symbol, name: `${symbol} Inc.`, price, previousClose, changePercent: ((price - previousClose) / previousClose) * 100, + currency: "USD", timestamp: NOW - 60_000, fetchedAt: NOW, delaySeconds: 0, + series: Array.from({ length: 60 }, (_, i) => previousClose + ((price - previousClose) * i) / 59), + open: previousClose, high: price, low: previousClose, periods: { pre: null, regular: [NOW - 1, NOW + 1], post: null }, + ...extra, +}); +const state = (overrides = {}) => ({ + symbols: ["AAPL", "NVDA", "BTC/USDT"], + quotes: { AAPL: quote("AAPL", 230.1, 227.3), NVDA: quote("NVDA", 138.4, 142.4, { delaySeconds: 900 }) }, + errors: {}, paused: false, loading: false, message: "", selected: 0, adding: false, input: "", notice: "", error: "", now: NOW, + ...overrides, +}); + +test("the chart is width by height, with the previous close as a rule", () => { + const rows = chartRows([10, 11, 12, 13], 9, 10, 4); + assert.equal(rows.length, 4); + for (const row of rows) assert.equal(row.map((run) => run.text).join("").length, 10); + const text = rows.map((row) => row.map((run) => run.text).join("")).join("\n"); + assert.match(text, /┄/); + // Four points fill four columns; the rest of the day is still empty. + assert.match(rows.at(-1).map((run) => run.text).join(""), /^\S{4}/); + assert.deepEqual(chartRows([1], 1, 10, 4), []); + // The day's high stays below the top row, clear of the text above the chart. + const tall = chartRows([10, 11, 12, 13], 9, 10, 10); + assert.equal(tall[0].map((run) => run.text).join("").trim(), ""); +}); + +test("every line of the pane fits its width, at any size", () => { + for (const [width, height] of [[48, 90], [48, 24], [36, 30], [80, 20], [24, 12], [120, 50]]) { + for (const colored of [PLAIN, palette(true)]) { + const { lines } = pane(state(), width, height, colored); + assert.ok(lines.length <= height, `${width}x${height}: ${lines.length} lines`); + for (const line of lines) assert.ok(cells(line) <= width, `${width}x${height}: ${cells(line)} > ${width}: ${strip(line)}`); + } + } +}); + +test("the pane shows quotes, sources, and the selected ticker's day when there's room", () => { + const tall = pane(state(), 48, 60).lines.join("\n"); + assert.match(tall, /◆ Pulse {2}3 tickers/); + assert.match(tall, /AAPL .* 230\.10 USD/); + assert.match(tall, /\+1\.23%/); + assert.match(tall, /Delay 15m/); + assert.match(tall, /BTC\/USDT +Waiting…/); + assert.match(tall, /Open +High +Low +Prev close/); + assert.match(tall, /Yahoo Finance · Binance Spot/); + assert.match(tall, /Pulse for Mac/); + assert.doesNotMatch(tall, /[▁▂▃▄▅▆▇]{3}.*230\.10/, "rows carry no line of their own"); + const short = pane(state(), 48, 18).lines.join("\n"); + assert.doesNotMatch(short, /Prev close/); +}); + +test("unknown delay is never shown as real time, and cached quotes say so", () => { + const unknown = state({ quotes: { AAPL: quote("AAPL", 230.1, 227.3, { delaySeconds: null }) }, symbols: ["AAPL"] }); + assert.match(detailScreen(unknown.quotes.AAPL, null, NOW, 60, 30).join("\n"), /Delay unknown/); + const cached = pane(state({ errors: { AAPL: "Yahoo rate limited requests." } }), 48, 30).lines.join("\n"); + assert.match(cached, /Cached quote · Yahoo rate limited/); + const paused = pane(state({ paused: true }), 48, 30).lines.join("\n"); + assert.match(paused, /Auto-refresh paused/); + assert.match(paused, /Not fetched/); +}); + +test("a pane six rows tall or less draws the one-line band", () => { + const { lines } = pane(state(), 60, 6); + assert.ok(pane(state(), 60, 7).lines.length > 1); + assert.equal(lines.length, 1); + assert.match(lines[0], /◆ Pulse {3}AAPL 230\.10 \+1\.23% {3}NVDA 138\.40 -2\.81%/); + assert.ok(cells(band(state(), 30)) <= 30); +}); + +test("text is cut by cells, counting wide characters twice", () => { + assert.equal(cells("腾讯控股"), 8); + assert.equal(fit("腾讯控股有限公司", 7), "腾讯控…"); + assert.equal(fit("AAPL", 10), "AAPL"); + assert.equal(cells(palette().link("https://x.test", "Pulse")), 5); + assert.deepEqual(wrap("Enter a ticker, such as AAPL, 0700.HK or ^GSPC", 20), ["Enter a ticker, such", "as AAPL, 0700.HK or", "^GSPC"]); +}); + +test("keys are read from raw terminal input", () => { + assert.deepEqual(keys("\x1b[A\x1b[Bq\r"), [{ name: "up" }, { name: "down" }, { name: "text", text: "q" }, { name: "enter" }]); + assert.deepEqual(keys("\x1b"), [{ name: "escape" }]); + assert.deepEqual(keys("\x1b[<0;5;7M\x1b[<0;5;7m"), [{ name: "click", x: 5, y: 7 }]); + // A late reply to the background-color query is skipped, not typed. + assert.deepEqual(keys("\x1b]11;rgb:0000/0000/0000\x1b\\a"), [{ name: "text", text: "a" }]); +}); + +// --------------------------------------------------------------------------- + +test("the watchlist file is shared: one process's edit is the next one's list", () => { + const dir = mkdtempSync(join(tmpdir(), "pulse-rex-")); + try { + const host = (store) => ({ load: store.load, save: store.save, fetch: async () => { throw new Error("offline"); }, now: () => NOW, sleep: async () => {}, changed() {} }); + const one = new Watchlist(host(createStore(dir))); + assert.deepEqual(one.preferences.symbols, ["AAPL", "NVDA", "^GSPC", "BTC/USDT"]); + assert.equal(one.add("700.hk"), "Added 0700.HK."); + one.pause(true); + const two = new Watchlist(host(createStore(dir))); + assert.ok(two.preferences.symbols.includes("0700.HK")); + assert.equal(two.preferences.paused, true); + assert.throws(() => two.add("Apple Inc"), /Enter a ticker/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("install adds one marked block at the end of init.lua, and uninstall takes it back out", () => { + const block = loaderBlock("/opt/pulse/lua/pulse.lua", ["/usr/bin/node", '/opt/pu"lse/bin/pulse-rex.js']); + assert.match(block, /dofile\("\/opt\/pulse\/lua\/pulse\.lua"\)\.setup\(\{ bin = \{ "\/usr\/bin\/node", "\/opt\/pu\\"lse\/bin\/pulse-rex\.js" \} \}\)/); + const config = 'rex.bind("cmd+b", "client.sidebar.toggle")\n'; + const added = withBlock(config, block); + assert.ok(added.startsWith(config)); + assert.ok(added.trimEnd().endsWith(END)); + assert.equal(withBlock(added, block), added); + const replaced = withBlock(added, loaderBlock("/new/pulse.lua", ["pulse-rex"])); + assert.equal(replaced.split(BEGIN).length, 2); + assert.match(replaced, /\/new\/pulse\.lua/); + assert.equal(withBlock(replaced, null), config); + assert.equal(withBlock("", block), block); + assert.equal(withBlock(config, null), config); +}); + +test("init.lua gets node and the package through a version manager's stable link", () => { + const dir = mkdtempSync(join(tmpdir(), "pulse-rex-node-")); + try { + // …/node/node-v22/{bin/node, lib/node_modules/rex-pulse-ticker}, and …/node/current -> node-v22 + const versioned = join(dir, "node", "node-v22"); + mkdirSync(join(versioned, "bin"), { recursive: true }); + mkdirSync(join(versioned, "lib", "node_modules", "rex-pulse-ticker"), { recursive: true }); + writeFileSync(join(versioned, "bin", "node"), ""); + chmodSync(join(versioned, "bin", "node"), 0o755); + symlinkSync(versioned, join(dir, "node", "current")); + const stable = join(dir, "node", "current"); + const paths = stablePaths({ PATH: `/nowhere:${join(stable, "bin")}` }, join(versioned, "bin", "node"), + join(versioned, "lib", "node_modules", "rex-pulse-ticker")); + assert.equal(paths.node, join(stable, "bin", "node")); + assert.equal(paths.bin, join(stable, "lib", "node_modules", "rex-pulse-ticker", "bin", "pulse-rex.js")); + // Without such a link, the paths node reports are kept. + const plain = stablePaths({ PATH: "/nowhere" }, join(versioned, "bin", "node"), join(versioned, "lib", "node_modules", "rex-pulse-ticker")); + assert.equal(plain.node, join(versioned, "bin", "node")); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("init.lua is found the way Rex finds it", () => { + assert.equal(configPath({ REX_CONFIG: "/x/init.lua", HOME: "/h" }), "/x/init.lua"); + assert.equal(configPath({ XDG_CONFIG_HOME: "/c", HOME: "/h" }), "/c/rex/init.lua"); + assert.equal(configPath({ HOME: "/h" }), "/h/.config/rex/init.lua"); +}); + +test("the Lua names every action pulse-rex's README lists", () => { + const lua = readFileSync(here("../lua/pulse.lua"), "utf8"); + const readme = readFileSync(here("../README.md"), "utf8"); + for (const name of lua.matchAll(/name = "(pulse_\w+)"/g)) assert.ok(readme.includes(name[1]), `README misses ${name[1]}`); +});