From fadeb17b6c6792b09bed4bda4807d73b731b1fce Mon Sep 17 00:00:00 2001 From: Pengboi Date: Sun, 26 Jul 2026 19:34:01 +0100 Subject: [PATCH 01/58] i18n: split the pure core out so the lib is Node-loadable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pure training helpers (history, progression, onerm, muscles, format, exercises) are deliberately self-contained — that is what lets them ship with their own vitest suites and got them reused across the React and mobile builds. They were one Vite-only call away from being loadable from plain Node too: `import.meta.glob` for the lazy locale packs, run at the top of i18n.js. Anything that imported `t` or `dateLocale` via the chain (i.e. every helper in src/lib) inherited the dependency. Splitting the runtime-agnostic state, constants and readers (t, dateLocale, instrFor, getLang, LANGS, INSTR_LANGS, DATE_LOCALES) into i18n-core.js lets plain Node require them. i18n.js keeps the Vite-only bits (the async setLang that lazy-loads locale packs via import.meta.glob and the React subscription hook useLang) and re-exports everything from core, so none of the 23 existing import sites change. exercises.js had one direct `import.meta.env` access for IMG_BASE/GIF_BASE — guarded with `?.` so the module resolves without Vite present. format.js and exercises.js import i18n-core directly; everything else still imports i18n.js. No public exports changed. 92/92 vitest tests pass; vite build still code-splits the locale packs the same way. --- frontend/src/lib/exercises.js | 12 ++++--- frontend/src/lib/format.js | 4 ++- frontend/src/lib/i18n-core.js | 58 +++++++++++++++++++++++++++++++++ frontend/src/lib/i18n.js | 61 ++++++++++++++--------------------- 4 files changed, 94 insertions(+), 41 deletions(-) create mode 100644 frontend/src/lib/i18n-core.js diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index 20d82d2..451929f 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -1,5 +1,7 @@ import { EXDB } from './exercises-data.js' -import { t } from './i18n.js' +// Imports i18n-core (not i18n.js) so this stays loadable from plain Node — the MCP server +// reuses EXIDX/musclesOf/etc. without dragging in the React + Vite-only i18n.js. +import { t } from './i18n-core.js' export { EXDB } export const EXIDX = {} @@ -28,9 +30,11 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB] // Media normally sits next to the app (img/ and gif/, mounted into the web container). // A build can point them somewhere else — the demo build pulls them off a CDN instead of -// shipping ~140 MB of images into the deployment. -const IMG_BASE = import.meta.env.VITE_IMG_BASE || 'img/' -const GIF_BASE = import.meta.env.VITE_GIF_BASE || 'gif/' +// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain +// Node; guard with `?.` so this module is loadable from Node without Vite (see i18n-core.js). +const ENV = import.meta.env || {} +const IMG_BASE = ENV.VITE_IMG_BASE || 'img/' +const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/' export const imgSrc = ex => IMG_BASE + ex.img export const gifSrc = ex => GIF_BASE + ex.gif diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js index de25f40..8eb4a46 100644 --- a/frontend/src/lib/format.js +++ b/frontend/src/lib/format.js @@ -1,5 +1,7 @@ // Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed). -import { dateLocale, t } from './i18n.js' +// Imports i18n-core (not i18n.js) so this pure helper stays loadable from plain Node — that's +// what lets the MCP server reuse it instead of reimplementing number/date formatting. +import { dateLocale, t } from './i18n-core.js' export const todayISO = () => { const d = new Date() return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') diff --git a/frontend/src/lib/i18n-core.js b/frontend/src/lib/i18n-core.js new file mode 100644 index 0000000..7bc5447 --- /dev/null +++ b/frontend/src/lib/i18n-core.js @@ -0,0 +1,58 @@ +// Pure, runtime-agnostic core of the i18n module. +// +// Split out of i18n.js so the pure-function training helpers (format.js, exercises.js and +// everything they import transitively — history, progression, onerm, muscles, demoSeed) can +// be required from plain Node too. That reuse is what lets the MCP server compute 1RM, muscle +// balance and progression prescriptions without re-implementing them — the same code that +// produces the numbers shown in the UI produces the numbers an LLM answers with. +// +// Everything browser-specific (React subscription hook, Vite's import.meta.glob lazy-loads of +// locale packs) stays in i18n.js, which re-exports these readers verbatim. + +export const LANGS = { + en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano', + pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文', + ko: '한국어', hi: 'हिन्दी' +} +export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko'] +export const DATE_LOCALES = { + en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', + pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN' +} + +// Mutable module state. `lang`/`dict`/`instr` are the readers' inputs; the browser-side +// `setLang` (in i18n.js) is the only writer, so they stay private to this module. +let lang = 'en' +let dict = {} +let instr = null // { exId: [steps] } for the current language, null = English +let version = 0 + +export const getLang = () => lang +export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB' +export const getVersion = () => version + +// Translate a source string; {0},{1}… are replaced with args (also on the English fallback). +export function t(s, ...args) { + let v = dict[s] || s + for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i]) + return v +} + +// Instructions for an exercise in the current language (English steps as fallback). +export const instrFor = ex => (instr && instr[ex.id]) || ex.st || [] + +/** + * Internal setter invoked by i18n.js's `setLang` once the locale pack has been loaded. + * Kept here — rather than just exported as `setLang` — because loading packs requires + * Vite's `import.meta.glob`, which would drag this file straight back into not being + * Node-safe. Returns the new version so the caller can notify its React subscribers. + * + * Both `dict` and `instr` may be passed as `null` to reset to English. + */ +export function _setLangState(newLang, newDict, newInstr) { + lang = LANGS[newLang] ? newLang : 'en' + dict = lang === 'en' ? {} : (newDict || {}) + instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null) + version++ + return version +} diff --git a/frontend/src/lib/i18n.js b/frontend/src/lib/i18n.js index ebade43..498eadc 100644 --- a/frontend/src/lib/i18n.js +++ b/frontend/src/lib/i18n.js @@ -1,56 +1,45 @@ -// Tiny dependency-free i18n. English source strings are the keys; locale files in -// src/locales/ map them to translations and are lazy-loaded (Vite code-splits each -// import.meta.glob entry), so the initial bundle stays English-only. -// Exercise instructions come from separately generated packs in src/instr/ (one per -// language, from the upstream dataset) — also lazy-loaded on language switch. +// Browser-only shell of the i18n module. +// +// Pure state, constants and readers (t, dateLocale, instrFor, getLang, LANGS, INSTR_LANGS) +// live in i18n-core.js so plain Node can reuse the training logic without a Vite environment. +// This file adds the two pieces that genuinely need the browser: the async `setLang` (which +// lazy-loads locale packs via import.meta.glob) and the React subscription hook `useLang` +// (which re-renders components on language switch). + import { useSyncExternalStore } from 'react' +import { + LANGS, INSTR_LANGS, DATE_LOCALES, + getLang, dateLocale, t, instrFor, getVersion, _setLangState +} from './i18n-core.js' -// UI languages. de/pt have no instruction pack upstream — instructions fall back to English. -export const LANGS = { - en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano', - pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文', - ko: '한국어', hi: 'हिन्दी' -} -export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko'] -const DATE_LOCALES = { - en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', - pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN' -} +// Re-export everything verbatim so existing callers (`import { t } from '../lib/i18n.js'`) +// keep working unchanged — the split is invisible at the import site. +export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor } +// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use +// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only. const localePacks = import.meta.glob('../locales/*.js') const instrPacks = import.meta.glob('../instr/*.js') -let lang = 'en' -let dict = {} -let instr = null // { exId: [steps] } for the current language, null = English -let version = 0 +// React subscription bookkeeping — kept here, not in core, so core has zero React coupling. const subs = new Set() -const notify = () => { version++; subs.forEach(f => f()) } - -export const getLang = () => lang -export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB' - -// Translate a source string; {0},{1}… are replaced with args (also on the English fallback). -export function t(s, ...args) { - let v = dict[s] || s - for (let i = 0; i < args.length; i++) v = v.replaceAll('{' + i + '}', args[i]) - return v -} -// Instructions for an exercise in the current language (English steps as fallback). -export const instrFor = ex => (instr && instr[ex.id]) || ex.st || [] +const notify = () => { subs.forEach(f => f()) } export async function setLang(l) { if (!LANGS[l]) l = 'en' - if (l === lang && version > 0) return - lang = l + // _setLangState mutates core state and bumps the version; we read it back for the + // subscription selector below. + if (l === getLang() && getVersion() > 0) return + let dict = {}, instr = null try { dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default } catch (e) { dict = {}; instr = null } + _setLangState(l, dict, instr) notify() } // Re-renders the subscribing component (and its children) whenever the language changes. export function useLang() { - return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, () => version) + return useSyncExternalStore(fn => { subs.add(fn); return () => subs.delete(fn) }, getVersion) } From 92914dea43963f4a7f12412172699bc3054dc08a Mon Sep 17 00:00:00 2001 From: Pengboi Date: Sun, 26 Jul 2026 19:34:09 +0100 Subject: [PATCH 02/58] MCP: read-only stdio server for LLM apps to query workout history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Model Context Protocol bridge that lets an external LLM application (Claude Desktop, Cursor, Cline, Continue, …) read a user's openGym profile directly from ./data — no new container, no extra auth, no third-party service. The LLM client spawns the server locally as a stdio process (per the official MCP model); reads the same state-.json the api server writes; reuses the pure training helpers from frontend/src/lib/*.js so the numbers it answers with match what the Stats screen shows exactly. Eight tools in v1, all read-only: · list_routines, get_routine — names + exercise counts + per-exercise targets · get_week_plan — Mo/We/Fr assignments and today's routine, accounting for any date-specific overrides (a "rest" override cancels the day) · list_workouts, get_workout — newest-first session summaries + per-set breakdown · get_bodyweight — weigh-ins with the goal line and signed deltas vs goal · estimate_1rm — Epley/Brzycki/Lombardi formulas, all-time best + trend per exercise, or a PR table across all reps-mode exercises · muscle_balance — which muscles are trained vs neglected over a week/month/all window State is read with fs.watch (mtime fallback for platforms where watchers are flaky) so the server reflects a session the web UI just finished without a restart. No passkey material, VAPID keys, or session secrets ever cross the boundary — handlers only ever serialize fields from the state object plus the user's name from db.json. The MCP server has exactly one runtime dependency beyond the SDK: none. zod is the SDK's transitive; vitest and Stryker are devDeps only. Tests run against the demo seed fixture (demoSeed.js) — 32 cases pinning the JSON shape and the most user-facing edge cases (empty state, missing routine, rest-day override, zero-workout muscle_balance, three 1RM formulas, superset links, timed/cardio set labels). --- mcp/README.md | 190 ++ mcp/package-lock.json | 4294 ++++++++++++++++++++++++++++++++++++++++ mcp/package.json | 26 + mcp/src/index.js | 63 + mcp/src/labels.js | 59 + mcp/src/state.js | 152 ++ mcp/src/tools.js | 362 ++++ mcp/test/tools.test.js | 474 +++++ mcp/vitest.config.js | 21 + 9 files changed, 5641 insertions(+) create mode 100644 mcp/README.md create mode 100644 mcp/package-lock.json create mode 100644 mcp/package.json create mode 100644 mcp/src/index.js create mode 100644 mcp/src/labels.js create mode 100644 mcp/src/state.js create mode 100644 mcp/src/tools.js create mode 100644 mcp/test/tools.test.js create mode 100644 mcp/vitest.config.js diff --git a/mcp/README.md b/mcp/README.md new file mode 100644 index 0000000..66d7d9e --- /dev/null +++ b/mcp/README.md @@ -0,0 +1,190 @@ +# openGym MCP server + +A [Model Context Protocol](https://modelcontextprotocol.io) bridge that lets an external LLM +application (Claude Desktop, Cursor, Cline, Continue, etc.) read your openGym profile — +routines, workouts, body-weight log, estimated 1RMs, and muscle balance — directly from your +self-hosted `./data` directory. + +It is read-only, runs locally as a stdio process spawned by the LLM client, adds no new +container, and requires no extra authentication. The LLM never sees passkeys, VAPID keys, or +session secrets — it can only read the same `state-.json` files the openGym api already +writes. + +The numbers it answers with are computed by the **same pure functions the React UI uses** +(`frontend/src/lib/*.js`) — `estimate1RM`, `loadOfWorkouts`, `effectiveRoutine`, etc. — so a +"what's my bench 1RM?" answer matches the Stats screen exactly. + +> Phase 1 of a multi-phase plan. Read-only today; long-lived token auth + write tools are +> planned but not shipped yet. See **Roadmap** below. + +## Quick start + +### 1. Install + +```bash +cd mcp +npm install +``` + +### 2. Point it at your data + +The MCP server reads the same `./data` directory `docker compose up` creates. Pick the profile +to answer for — its user id is in `./data/db.json` under `users[].id`: + +```bash +# single-user instance (the common self-hosted case) — auto-detected: +node src/index.js + +# multi-user instance, or just to be explicit: +OPENGYM_UID= OPENGYM_DATA=/path/to/openGym/data node src/index.js +``` + +### 3. Register with your LLM client + +Add the server to your LLM client's MCP config. For Claude Desktop, edit +`claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`): + +```jsonc +{ + "mcpServers": { + "opengym": { + "command": "node", + "args": ["/absolute/path/to/openGym/mcp/src/index.js"], + "env": { + "OPENGYM_DATA": "/absolute/path/to/openGym/data", + "OPENGYM_UID": "" // optional — auto-detected if you have one profile + } + } + } +} +``` + +For Cursor and other MCP-compatible clients, see the client's MCP docs — the same `command` + +`args` + `env` shape is what every stdio MCP server expects. + +Restart the client; you should see the openGym tools appear with "serving profile \" on +the server's stderr. + +## Tools + +Eight read-only tools in v1: + +| Tool | What it answers | +|---|---| +| `list_routines` | What routines are saved in my profile? (names + exercise counts) | +| `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) | +| `get_week_plan` | What's on my plan this week, including today with any date-specific override? | +| `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. | +| `get_workout` | Full set-by-set breakdown of one date's session. | +| `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. | +| `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. | +| `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. | + +Each tool returns JSON the LLM can format as it likes; structured fields (sets, dates, levels) +are pre-formatted into human-readable labels in `src/labels.js` so the LLM doesn't need to +re-interpret them. + +## How it reuses the training logic + +openGym deliberately keeps its training logic in pure functions under `frontend/src/lib/` with +unit tests next to them (see `CONTRIBUTING.md` — "Training logic gets a unit test"). The MCP +server imports those files directly as Node ESM and calls the same functions the UI does: + +``` +mcp/src/tools.js + └── list_workouts handler ──▶ frontend/src/lib/history.js (workoutVolume, setsDone) + └── estimate_1rm handler ──▶ frontend/src/lib/onerm.js (best1RM, e1rmSeries) + └── muscle_balance ──▶ frontend/src/lib/muscles.js (loadOfWorkouts, rankOf, levelsOf) + └── get_week_plan ──▶ frontend/src/lib/history.js (effectiveRoutine, effectiveRoutineId) +``` + +The one lib file that wasn't Node-safe was `i18n.js` (it used Vite's `import.meta.glob`) +— split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React-specific bits, re-exports +from core). `exercises.js` got a one-line guard against `import.meta.env` being undefined in +plain Node. No new dependencies landed in `frontend/`, no public exports changed. + +## Design constraints honoured + +- **One runtime dependency beyond the MCP SDK:** none. `mcp/package.json` declares only + `@modelcontextprotocol/sdk` + its transitive `zod`. No database driver, no HTTP framework. +- **No new container.** stdio transport is spawned by the LLM client; nothing to add to + `docker-compose.yml`. +- **No new auth.** The filesystem is the boundary — same as `docker compose` running on the + user's box. The MCP server only sees what its host process can already see. +- **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client + disconnects. Matches the openGym ethos from `README.md`. +- **State-On-Disk source of truth.** Uses `fs.watch` to pick up sessions the web UI just + finished, with an mtime fallback for platforms where watchers are flaky. + +## Tests + +```bash +cd mcp && npm test +``` + +Tool-layer tests (32 of them) seed state from `frontend/src/lib/demoSeed.js` — the same +deterministic fixture the public demo deployment runs on. The pure lib functions themselves +already have 92 tests of their own in `frontend/src/lib/*.test.js`. + +Three things the suite is deliberate about: +- **Pinned fake time.** `vi.useFakeTimers({ now: new Date('2026-07-27T12:00:00Z'), toFake: + ['Date'] })` freezes "today" to a Monday so date-dependent tools (`get_week_plan`, + `muscle_balance`) see consistent values. `toFake: ['Date']` only mocks the Date object — + `fs.watch`, `setTimeout` etc. keep working with the real event loop. +- **Real numeric assertions** for a representative case per tool: hand-computed Epley 1RM + (`152.5×12 → 213.5`), hand-computed body-weight delta (`78.5 − 77 = 1.5`), exact workout + volume (`18500` kg). Structure-only assertions ("est > 0") are kept for the cases where the + pure lib has its own tests already. +- **Negative cases.** Empty state, missing routine, missing workout, reversed date range, + no goal set, zero-workout `muscle_balance`, fresh-account no-state fallback for every tool. + +## Mutation testing + +```bash +cd mcp && npm run mutation:test +``` + +Uses [Stryker](https://stryker-mutator.io) to mutate `src/state.js`, `src/labels.js` and +`src/tools.js` (the three MCP-only modules — the reused pure lib in `frontend/src/lib/` is +excluded since it has its own 92-test vitest suite). Config lives at `.stryker.conf.json`. + +**Run mode:** `inPlace: true`. Stryker mutates files where they live (so the test file's +relative imports `../../frontend/src/lib/*.js` keep resolving), keeps a backup in +`.stryker-tmp/backup-*/` during the run, and restores on exit — verified: after the run, +`git diff` shows no changes and all tests still pass. If Stryker is killed hard (SIGKILL, +power loss) the next run restores from the backup before mutating again. + +**Baseline (first run, 847 mutants):** + +| File | Score | Killed | Survived | No cov | +|---|---:|---:|---:|---:| +| `state.js` | 3.92% | 6 | 26 | 121 | +| `labels.js` | 23.64% | 13 | 25 | 17 | +| `tools.js` | 49.14% | 314 | 279 | 46 | +| **Total** | **39.32%** | 333 | 330 | 184 | + +The 39% baseline is honest about how much of the *handler* logic the test suite genuinely +exercises — many of the survivors are zod schema declarations (e.g. `period: +z.enum(['week', 'month', 'all'])`) which mutation-testing finds hard to kill without testing +the SDK's validation layer that the unit suite deliberately bypasses. Treat the score as a +lower bound: every "no cov" mutant is a code path the suite hasn't even reached; each is a +TODO on its own. Iterate; aim for 70%+ before the MCP server moves from v0.1 to v1. + +Report at `mcp/reports/mutation/mutation.html` (open in a browser, click any file to see +survived mutants inline). + +## Roadmap + +- **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access. +- **Phase 1.5:** `progression_next` (what does the policy prescribe next?) + `search_exercises` + (search the catalog). No new deps; small surface area. +- **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the + admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify- + write of `state-.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`, + `assign_weekday`, `override_day`. +- **Phase 3:** Streamable HTTP transport, opt-in 4th container in `docker-compose.yml`. Same + tool implementations, second transport — the MCP SDK supports both behind one tool registration. + +## License + +AGPL-3.0-or-later, same as openGym. diff --git a/mcp/package-lock.json b/mcp/package-lock.json new file mode 100644 index 0000000..da4fbad --- /dev/null +++ b/mcp/package-lock.json @@ -0,0 +1,4294 @@ +{ + "name": "opengym-mcp", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "opengym-mcp", + "version": "0.1.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.0.4", + "zod": "^3.23.8" + }, + "bin": { + "opengym-mcp": "src/index.js" + }, + "devDependencies": { + "@stryker-mutator/core": "^9.6.1", + "@stryker-mutator/vitest-runner": "^9.6.1", + "vitest": "^4.1.10" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", + "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-annotate-as-pure": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", + "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-create-class-features-plugin": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz", + "integrity": "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-optimise-call-expression": "^7.29.7", + "@babel/helper-replace-supers": "^7.29.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", + "@babel/traverse": "^7.29.7", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-member-expression-to-functions": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", + "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-optimise-call-expression": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz", + "integrity": "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-replace-supers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", + "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-member-expression-to-functions": "^7.29.7", + "@babel/helper-optimise-call-expression": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-skip-transparent-expression-wrappers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", + "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-proposal-decorators": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.29.7.tgz", + "integrity": "sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-create-class-features-plugin": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/plugin-syntax-decorators": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-decorators": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.29.7.tgz", + "integrity": "sha512-9MTTLbF39X6sqM92JPEsoI7++26hjZvzkxKZy64aMhWLH2mPkJ/Q3AV4QLmls3R14FpSpkOwQQfUh962JGQxxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-destructuring": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.7.tgz", + "integrity": "sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-explicit-resource-management": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.29.7.tgz", + "integrity": "sha512-Rstj7coNz8sE+7Ju7ihpHLI564lsK5pUpNNlvptCIC/16E/S5hbl6n3kESPKdNRmqEWlpn5xpS5Q2dvXBsySLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/plugin-transform-destructuring": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-modules-commonjs": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", + "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-typescript": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.7.tgz", + "integrity": "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.29.7", + "@babel/helper-create-class-features-plugin": "^7.29.7", + "@babel/helper-plugin-utils": "^7.29.7", + "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", + "@babel/plugin-syntax-typescript": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/preset-typescript": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.28.5.tgz", + "integrity": "sha512-+bQy5WOI2V6LJZpPVxY+yp66XdZ2yifu0Mc1aP5CQKgjn4QM5IN2i5fAZ4xKop47pr8rpVhiAeu+nDQa12C8+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1", + "@babel/helper-validator-option": "^7.27.1", + "@babel/plugin-syntax-jsx": "^7.27.1", + "@babel/plugin-transform-modules-commonjs": "^7.27.1", + "@babel/plugin-transform-typescript": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", + "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", + "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", + "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", + "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@hono/node-server": { + "version": "1.19.15", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.15.tgz", + "integrity": "sha512-Za2ai6TLdKjUvnur+eenO6nuYYipVAEhyCAdaV8IRvmU9kK8crOZUSYvIXn72E4f8fJqyAbpcJuTsYYmZp9Deg==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.7.tgz", + "integrity": "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.1.tgz", + "integrity": "sha512-b6xmA/VlTe0ZgDQHDui+Nav470u7u49nRd8/iuhOcQPO9Ch7lGuogydhi2VOmNlZ+zXcM8IcPuNSwQcdJaF/kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.7", + "@inquirer/core": "^11.2.1", + "@inquirer/figures": "^2.0.7", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.1.1.tgz", + "integrity": "sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "11.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-11.2.1.tgz", + "integrity": "sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.7", + "@inquirer/figures": "^2.0.7", + "@inquirer/type": "^4.0.7", + "cli-width": "^4.1.0", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/editor": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.2.2.tgz", + "integrity": "sha512-ZRVd/oD+sYsUd5zVm0NflqEzlqfYCyHNsqkHl2oWXEUHs12tCbcSFi+wVFEvD8+LGRaMUsVrE7qeo6lSG/S1Vg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/external-editor": "^3.0.3", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.1.tgz", + "integrity": "sha512-YmQpenjbFSHAK3sOd44puHh3V1KXXr+JiNpUztoSQ4drLh2rTVzTap/YtlAVu/5xavifIlBfNEzJ/neZJ1a/1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.3.tgz", + "integrity": "sha512-6thf5I8q7lZwzGLAxPaaGEREEkZ3nyePPDQ1oyobblxmEE8mqTLguScP7pDjUTAibiyb4hfXl+qjUEJ+di/aNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/figures": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.7.tgz", + "integrity": "sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.2.tgz", + "integrity": "sha512-9K/DDBSQpOyZSkt6sOVP9Vo0TR7atX2kuILsUu0x3wVcVbe97lJwIJKMLdMw25tDYuXl/qp6erT0Xs1rfmcfZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.1.1.tgz", + "integrity": "sha512-XF4IXAbPnGPgw0wsbC/i2tPcyfdZgDpUlhsqU0SfT4IRIGWha6Xm9VRgN5yYxJq+jnyXlfXI/nQ3ulfk0iEICA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.1.1.tgz", + "integrity": "sha512-3XBfF7DAsp5qeDsvN5Rd1HmbNokVvEQoUM0QLrRcybC9nX96w3Pbmu7qUsb3IT3J3jBvs2+mTXaKHOUsgHMLzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.7", + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.5.2.tgz", + "integrity": "sha512-IYR/3C/paEVVQYQvdDlFZVjRCJVYHHON0XXMH91KO9GSxs0TdKYWlUdvfQl2EfAHDxUaN3IBffkE/BDTh5nJ6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.2.1", + "@inquirer/confirm": "^6.1.1", + "@inquirer/editor": "^5.2.2", + "@inquirer/expand": "^5.1.1", + "@inquirer/input": "^5.1.2", + "@inquirer/number": "^4.1.1", + "@inquirer/password": "^5.1.1", + "@inquirer/rawlist": "^5.3.1", + "@inquirer/search": "^4.2.1", + "@inquirer/select": "^5.2.1" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.1.tgz", + "integrity": "sha512-QqdTqQddL3qPX/PPrjobpsO25NZ4dWXgTLenrR445L2ptLEYE6Z+PD5c5CNDJNx4ugRgELAIpSIJxZaO2jJ2Og==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.2.1.tgz", + "integrity": "sha512-xJj8QWKRSrfKoBIITLZK61dD3zwo0Rz11fgDImku30/Oe81zMdIdGgrLY2h6RkJ+KZ/GhNYIRMKnH/62qBTA5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.2.1", + "@inquirer/figures": "^2.0.7", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.1.tgz", + "integrity": "sha512-FlDndEUww8m7BfukO2nJa25vhD+H5jxxCv4oGioKqzyWz3nPHhhw4LKdYRSlXuAx7DsdWia7iyaBPKKS95Evfw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.7", + "@inquirer/core": "^11.2.1", + "@inquirer/figures": "^2.0.7", + "@inquirer/type": "^4.0.7" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.0.7.tgz", + "integrity": "sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", + "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", + "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.139.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz", + "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz", + "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz", + "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz", + "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz", + "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz", + "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz", + "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz", + "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz", + "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz", + "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz", + "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz", + "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz", + "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz", + "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.11.1", + "@emnapi/runtime": "1.11.1", + "@napi-rs/wasm-runtime": "^1.1.6" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz", + "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz", + "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sec-ant/readable-stream": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", + "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@sindresorhus/merge-streams": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", + "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@stryker-mutator/api": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@stryker-mutator/api/-/api-9.6.1.tgz", + "integrity": "sha512-g8VNoFWQWbx0pdal3Vt8jVCZW+v3sc3gi94iI0GVtVgUGTqphAjJF6EAruPTx0lqvtonsaAxn5TD36hcG1d6Wg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "mutation-testing-metrics": "3.7.3", + "mutation-testing-report-schema": "3.7.3", + "tslib": "~2.8.0", + "typed-inject": "~5.0.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@stryker-mutator/core": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@stryker-mutator/core/-/core-9.6.1.tgz", + "integrity": "sha512-WMgnvf+Wyh/yiruhNZwc8w8DlzmmjXhPjSn5MR8RhAXzlnWji8TQrUYgBUkHk9bEgSaIlB3KZHm37iiU5Q2cLQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@inquirer/prompts": "^8.0.0", + "@stryker-mutator/api": "9.6.1", + "@stryker-mutator/instrumenter": "9.6.1", + "@stryker-mutator/util": "9.6.1", + "ajv": "~8.18.0", + "chalk": "~5.6.0", + "commander": "~14.0.0", + "diff-match-patch": "1.0.5", + "emoji-regex": "~10.6.0", + "execa": "~9.6.0", + "json-rpc-2.0": "^1.7.0", + "lodash.groupby": "~4.6.0", + "minimatch": "~10.2.4", + "mutation-server-protocol": "~0.4.0", + "mutation-testing-elements": "3.7.3", + "mutation-testing-metrics": "3.7.3", + "mutation-testing-report-schema": "3.7.3", + "npm-run-path": "~6.0.0", + "progress": "~2.0.3", + "rxjs": "~7.8.1", + "semver": "^7.6.3", + "source-map": "~0.7.4", + "tree-kill": "~1.2.2", + "tslib": "2.8.1", + "typed-inject": "~5.0.0", + "typed-rest-client": "~2.3.0" + }, + "bin": { + "stryker": "bin/stryker.js" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@stryker-mutator/core/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@stryker-mutator/instrumenter": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@stryker-mutator/instrumenter/-/instrumenter-9.6.1.tgz", + "integrity": "sha512-5K8wH4Pthly25c2uKKik4Dfcoeou7sbJdFS6u3QIYHlulgFVDJwtEMWTZGkZfs7IiUEXIDNa0keRACq5jn5AvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@babel/core": "~7.29.0", + "@babel/generator": "~7.29.0", + "@babel/parser": "~7.29.0", + "@babel/plugin-proposal-decorators": "~7.29.0", + "@babel/plugin-transform-explicit-resource-management": "^7.28.0", + "@babel/preset-typescript": "~7.28.0", + "@stryker-mutator/api": "9.6.1", + "@stryker-mutator/util": "9.6.1", + "angular-html-parser": "~10.4.0", + "semver": "~7.7.0", + "tslib": "2.8.1", + "weapon-regex": "~1.3.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@stryker-mutator/instrumenter/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@stryker-mutator/util": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@stryker-mutator/util/-/util-9.6.1.tgz", + "integrity": "sha512-Lk/ALVctJjFv1vvwR+CFoKzDCWvsBlq7flDUnmnpuwTrGbm156EdZD1Jjq4o8KdOap0ezUZqQNE9OAI1m2+pUQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/@stryker-mutator/vitest-runner": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@stryker-mutator/vitest-runner/-/vitest-runner-9.6.1.tgz", + "integrity": "sha512-eyUHTCf3Ui+SUn/tpFJwzw6MV391kyBLZk/cDHFUfKFELqKMLbvd7e81axArlApKqO6cOnLfrxlwED+2SRN0ow==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@stryker-mutator/api": "9.6.1", + "@stryker-mutator/util": "9.6.1", + "semver": "^7.7.4", + "tslib": "~2.8.0" + }, + "engines": { + "node": ">=14.18.0" + }, + "peerDependencies": { + "@stryker-mutator/core": "9.6.1", + "vitest": ">=2.0.0" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", + "integrity": "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitest/expect": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz", + "integrity": "sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.10.tgz", + "integrity": "sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.10", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.10.tgz", + "integrity": "sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.10.tgz", + "integrity": "sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.10", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.10.tgz", + "integrity": "sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "@vitest/utils": "4.1.10", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.10.tgz", + "integrity": "sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.10.tgz", + "integrity": "sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.10", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/angular-html-parser": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/angular-html-parser/-/angular-html-parser-10.4.0.tgz", + "integrity": "sha512-++nLNyZwRfHqFh7akH5Gw/JYizoFlMRz0KRigfwfsLqV8ZqlcVRb1LkPEWdYvEKDnbktknM2J4BXaYUGrQZPww==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.4", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.4.tgz", + "integrity": "sha512-s4+sLr9mZ/CyqeRritFeYV/Zx73OAtmaHn6kkBS1XRoJn1hrg3xIDUcpicAEX68tkcIN0iBCgti31C8zxtkhsQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", + "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/browserslist": { + "version": "4.28.7", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz", + "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.44", + "caniuse-lite": "^1.0.30001806", + "electron-to-chromium": "^1.5.393", + "node-releases": "^2.0.51", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001806", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", + "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz", + "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/des.js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.1.0.tgz", + "integrity": "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff-match-patch": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz", + "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/electron-to-chromium": { + "version": "1.5.396", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", + "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.1.tgz", + "integrity": "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz", + "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/execa": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", + "integrity": "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sindresorhus/merge-streams": "^4.0.0", + "cross-spawn": "^7.0.6", + "figures": "^6.1.0", + "get-stream": "^9.0.0", + "human-signals": "^8.0.1", + "is-plain-obj": "^4.1.0", + "is-stream": "^4.0.1", + "npm-run-path": "^6.0.0", + "pretty-ms": "^9.2.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^4.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": "^18.19.0 || >=20.5.0" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.6.0", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.0.tgz", + "integrity": "sha512-XKJXDsASUOo0LLtFwW5hCcQGH0N4WQc/Rn8/Pvoia+TJFOkkFPvrtW9lZOeeNcxQJspvOIERMwiRLsVFlhHEkA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-uri": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", + "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", + "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-string-width": "^3.0.2" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/figures": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", + "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-stream": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", + "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sec-ant/readable-stream": "^0.4.1", + "is-stream": "^4.0.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.32", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.32.tgz", + "integrity": "sha512-XcuyW9qE2kJn07PkecMOBd5Vq/hMy7mmGw+idz1yblbg9N17ijJODrvPkn7/dwL3Kulj8LcRJ69DLOWf91dRUg==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/human-signals": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", + "integrity": "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ip-address": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz", + "integrity": "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-plain-obj": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/is-stream": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", + "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.4", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.4.tgz", + "integrity": "sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/js-md4": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/js-md4/-/js-md4-0.3.2.tgz", + "integrity": "sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-rpc-2.0": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/json-rpc-2.0/-/json-rpc-2.0-1.7.1.tgz", + "integrity": "sha512-JqZjhjAanbpkXIzFE7u8mE/iFblawwlXtONaCvRqI+pyABVz7B4M1EUNpyVW+dZjqgQ2L5HFmZCmOCgUKm00hg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lodash.groupby": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", + "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", + "dev": true, + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true, + "license": "ISC" + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mutation-server-protocol": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/mutation-server-protocol/-/mutation-server-protocol-0.4.1.tgz", + "integrity": "sha512-SBGK0j8hLDne7bktgThKI8kGvGTx3rY3LAeQTmOKZ5bVnL/7TorLMvcVF7dIPJCu5RNUWhkkuF53kurygYVt3g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.1.12" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/mutation-server-protocol/node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/mutation-testing-elements": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/mutation-testing-elements/-/mutation-testing-elements-3.7.3.tgz", + "integrity": "sha512-SMeIPxngJpfjfNYctFpYQQtlBlZaVO0aoB3FKdwrI8Ee/2bkyUuCZzAOCLv1U9fnmfA37dPFq0Owduoxs2XgGQ==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/mutation-testing-metrics": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/mutation-testing-metrics/-/mutation-testing-metrics-3.7.3.tgz", + "integrity": "sha512-B8QrP0ZomErzTPNlhrzKWPNBln+3afwBZPHv0Q7N8wZZTYxMptzb/Gdm3ExXVmioVYrtZAtsDs7W/T/b2AixOQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "mutation-testing-report-schema": "3.7.3" + } + }, + "node_modules/mutation-testing-report-schema": { + "version": "3.7.3", + "resolved": "https://registry.npmjs.org/mutation-testing-report-schema/-/mutation-testing-report-schema-3.7.3.tgz", + "integrity": "sha512-BHm3MYq+ckO+t5CtlG8zpqxc75rdJCkxVlE+fGuGJM3F7tNCQ/OW2N+TQVHN3BHsYa84+BFc6g3AwDYkUsw2MA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", + "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-releases": { + "version": "2.0.51", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", + "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/npm-run-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz", + "integrity": "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0", + "unicorn-magic": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.4.tgz", + "integrity": "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parse-ms": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", + "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/postcss": { + "version": "8.5.23", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz", + "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.16", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/pretty-ms": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz", + "integrity": "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse-ms": "^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rolldown": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz", + "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.139.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.1.5", + "@rolldown/binding-darwin-arm64": "1.1.5", + "@rolldown/binding-darwin-x64": "1.1.5", + "@rolldown/binding-freebsd-x64": "1.1.5", + "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", + "@rolldown/binding-linux-arm64-gnu": "1.1.5", + "@rolldown/binding-linux-arm64-musl": "1.1.5", + "@rolldown/binding-linux-ppc64-gnu": "1.1.5", + "@rolldown/binding-linux-s390x-gnu": "1.1.5", + "@rolldown/binding-linux-x64-gnu": "1.1.5", + "@rolldown/binding-linux-x64-musl": "1.1.5", + "@rolldown/binding-openharmony-arm64": "1.1.5", + "@rolldown/binding-wasm32-wasi": "1.1.5", + "@rolldown/binding-win32-arm64-msvc": "1.1.5", + "@rolldown/binding-win32-x64-msvc": "1.1.5" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/std-env": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz", + "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-final-newline": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", + "integrity": "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", + "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/typed-inject": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/typed-inject/-/typed-inject-5.0.0.tgz", + "integrity": "sha512-0Ql2ORqBORLMdAW89TQKZsb1PQkFGImFfVmncXWe7a+AA3+7dh7Se9exxZowH4kbnlvKEFkMxUYdHUpjYWFJaA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/typed-rest-client": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-2.3.1.tgz", + "integrity": "sha512-k4kX5Up6qA68D0Cby2AK+6+vM5k3qTxe+/3FqhnHRExjY5cfbOnzjQZbP/LXleF8hVoDvDqxlgk9KK83HoBZlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "des.js": "^1.1.0", + "js-md4": "^0.3.2", + "qs": "6.15.1", + "tunnel": "0.0.6", + "underscore": "^1.13.8" + }, + "engines": { + "node": ">= 16.0.0" + } + }, + "node_modules/typed-rest-client/node_modules/qs": { + "version": "6.15.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", + "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/underscore": { + "version": "1.13.8", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz", + "integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicorn-magic": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", + "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vite": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.5.tgz", + "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.17", + "rolldown": "~1.1.5", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.3.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.10.tgz", + "integrity": "sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.10", + "@vitest/mocker": "4.1.10", + "@vitest/pretty-format": "4.1.10", + "@vitest/runner": "4.1.10", + "@vitest/snapshot": "4.1.10", + "@vitest/spy": "4.1.10", + "@vitest/utils": "4.1.10", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.10", + "@vitest/browser-preview": "4.1.10", + "@vitest/browser-webdriverio": "4.1.10", + "@vitest/coverage-istanbul": "4.1.10", + "@vitest/coverage-v8": "4.1.10", + "@vitest/ui": "4.1.10", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/weapon-regex": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/weapon-regex/-/weapon-regex-1.3.6.tgz", + "integrity": "sha512-wsf1m1jmMrso5nhwVFJJHSubEBf3+pereGd7+nBKtYJ18KoB/PWJOHS3WRkwS04VrOU0iJr2bZU+l1QaTJ+9nA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yoctocolors": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", + "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + } + } +} diff --git a/mcp/package.json b/mcp/package.json new file mode 100644 index 0000000..d72b57f --- /dev/null +++ b/mcp/package.json @@ -0,0 +1,26 @@ +{ + "name": "opengym-mcp", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "MCP (Model Context Protocol) bridge for openGym — lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.", + "license": "AGPL-3.0-or-later", + "main": "src/index.js", + "bin": { + "opengym-mcp": "src/index.js" + }, + "scripts": { + "start": "node src/index.js", + "test": "vitest run", + "mutation:test": "stryker run" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.0.4", + "zod": "^3.23.8" + }, + "devDependencies": { + "@stryker-mutator/core": "^9.6.1", + "@stryker-mutator/vitest-runner": "^9.6.1", + "vitest": "^4.1.10" + } +} diff --git a/mcp/src/index.js b/mcp/src/index.js new file mode 100644 index 0000000..9ef03a1 --- /dev/null +++ b/mcp/src/index.js @@ -0,0 +1,63 @@ +#!/usr/bin/env node +// openGym MCP server — stdio transport, read-only tools over a single user's state file. +// +// Spawning model (per the official MCP design): the LLM client (Claude Desktop, Cursor, +// Cline, …) starts this process locally, talks JSON-RPC over stdin/stdout, and tears it down +// when the session ends. That matches openGym's "your data stays in a folder you control" +// ethos — no extra container, no new outbound network, no third-party service. +// +// Env: +// OPENGYM_DATA directory containing db.json + state-.json (default: ./data) +// OPENGYM_UID which profile to answer for (default: auto-detect the single-user case) +// OPENGYM_LANG reserved for future label-localisation (default: en) +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' +import { TOOLS } from './tools.js' +import { init, getUser } from './state.js' + +const server = new McpServer({ + name: 'opengym', + version: '0.1.0' +}) + +// Initialise the state view up-front so a bad config (missing data dir, ambiguous uid) fails +// fast with a clear message on stderr rather than silently answering every tool call with the +// "no synced state" fallback. init() is idempotent — the LLM client restart is cheap. +try { + init() + // Always register every tool, regardless of whether state resolved — an LLM client that + // learns the tool list at handshake should see all eight. The handlers themselves degrade + // gracefully if state is null (returns the no-state sentinel object). + const u = getUser() + console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`) +} catch (e) { + console.error(`[opengym-mcp] ${e.message}`) + // Don't exit — keep the server up so the LLM client still gets tool listings and a useful + // error if it tries to call one. Most issues are env-shaped (wrong OPENGYM_DATA path) and + // a user will restart once they fix it; failing at handshake is more annoying than a clear + // runtime error. +} + +for (const t of TOOLS) { + server.tool( + t.name, + t.description, + t.schema, + async (params) => { + try { + const result = t.handler(params || {}) + return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] } + } catch (err) { + const code = err.code || 'ERROR' + return { + isError: true, + content: [{ type: 'text', text: `${code}: ${err.message}` }] + } + } + } + ) +} + +const transport = new StdioServerTransport() +await server.connect(transport) +// Process stays alive serving JSON-RPC over stdio until the LLM client disconnects. diff --git a/mcp/src/labels.js b/mcp/src/labels.js new file mode 100644 index 0000000..6462382 --- /dev/null +++ b/mcp/src/labels.js @@ -0,0 +1,59 @@ +// Formatting glue between pure lib helpers and the JSON the MCP tools return to an LLM. +// +// The lib modules speak in compact codes (e.g. `nextPrescription.why` is [template, ...args]) +// because the UI also needs to translate them. An LLM doesn't read templates, so the tools +// format each value into final English text before serialising. Keeping this in one place +// means a fix to a phrasing lands in every tool at once. +import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js' +import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js' +import { POLICY_NAME } from '../../frontend/src/lib/progression.js' +import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js' + +/** Apply {0},{1},… substitutions to the template strings the lib returns. */ +export function fmt(template, args) { + let v = template + for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i])) + return v +} + +/** Pre-formatted label for one set, e.g. "5 @ 60 kg", "1:30 · 20 kg", "20 min @ 8 km/h". */ +export { setLabel } + +/** A one-line description of a routine entry, e.g. "3 × 10 · 60 kg". Accepts a cfg + unit. */ +export function exLine(cfg, unit) { + const mode = modeOf(cfg) + const n = cfg.sets || 1 + const load = cfg.weight ? ' · ' + fmtNum(cfg.weight) + ' ' + unit : '' + if (mode === 'cardio') return `${n} × ${cfg.min || 20} min @ ${fmtNum(cfg.speed || 8)} km/h` + if (mode === 'time') return `${n} × ${fmtSec(cfg.sec || 45)}${load}` + return `${n} × ${cfg.reps}${load}` +} + +/** A human name for a muscle slug, falling back to the slug if unmapped. */ +export function muscleName(slug) { + return MUSCLE_NAME[slug] || slug +} + +/** English name of a progression policy, falling back to the slug. */ +export function policyName(policy) { + return POLICY_NAME[policy] || policy +} + +/** Friendly month-day for an ISO date ("3 Jul"); used in summaries so the LLM reads natural. */ +export function friendlyDate(iso) { + if (!iso) return null + return fmtDate(iso) +} + +/** Duration in minutes ("46 min", "1h 14m"). */ +export function friendlyDuration(ms) { + return ms ? fmtDur(ms) : null +} + +/** Sums vs planned and returns a "{done}/{total}" label. */ +export function ratio(done, total) { + return `${done}/${total}` +} + +/** Returns the muscle slugs in head-to-toe order (the same order UI lists them). */ +export function muscleOrder() { return MUSCLES.slice() } diff --git a/mcp/src/state.js b/mcp/src/state.js new file mode 100644 index 0000000..8ce0c6e --- /dev/null +++ b/mcp/src/state.js @@ -0,0 +1,152 @@ +// State accessor — opens ./data/state-.json (+ db.json for the user record), caches it, +// and re-reads via fs.watch so tools reflect a session the web UI just finished without a +// server restart. Read-only by design: nothing in the MCP server ever writes to these files, +// which keeps it consistent with the api server's own read-on-write view of state. +// +// The state shape comes straight from frontend/src/store/useStore.js DEF; the runtime fields +// that stay device-local (`active`) never reach the file — see api server.js PUT /api/data. +import fs from 'node:fs' +import path from 'node:path' + +const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data') + +// Cached state. `null` means "no state file for this user" (e.g. brand-new account that never +// signed in on a device). `undefined` means "not yet loaded". +let _state = undefined +let _db = undefined +let _uid = null +let _watcher = null +let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions + +/** A safe read of a JSON file; returns null on missing/invalid rather than throwing. */ +function readJsonOrNull(file) { + try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null } +} + +function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } } + +function stateFile(uid) { + return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json') +} + +/** + * Resolve which user the MCP server should answer for. + * + * Strategy, in order: + * 1. OPENGYM_UID env — explicit choice on multi-user instances. + * 2. Exactly one state file in ./data — the common self-hosted single-user case. + * 3. Exactly one user in db.json with no state file yet — same intent, brand-new account. + * 4. Otherwise: throw with the list of options so the user can pick. + * + * The uid pattern `^[a-zA-Z0-9_-]+$` matches what api/server.js emits (base64url of 12 random + * bytes), and the sanitise on stateFile() above keeps a sneaky `..` in OPENGYM_UID harmless. + */ +function resolveUid() { + const envUid = (process.env.OPENGYM_UID || '').trim() + if (envUid) { + if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`OPENGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`) + return envUid + } + const files = fs.readdirSync(DATA_DIR) + .filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f)) + .map(f => f.replace(/^state-/, '').replace(/\.json$/, '')) + if (files.length === 1) return files[0] + if (files.length === 0) { + reloadDb() + if (_db.users.length === 1) return _db.users[0].id + if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`) + } + throw new Error( + `multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` + + ` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)` + ) +} + +/** Set up the live state view: pick the uid, load db.json, attach the watcher, prime state. */ +export function init() { + if (_uid !== null) return // idempotent + if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`) + _uid = resolveUid() + reloadDb() + const file = stateFile(_uid) + if (fs.existsSync(file)) { + _state = readJsonOrNull(file) + if (_state) _state = Object.assign({}, defaultsShape(), _state) + try { _loadedMtime = fs.statSync(file).mtimeMs } catch {} + } + if (_watcher) _watcher.close() + // fs.watch is best-effort: the watcher may briefly drop events under some filesystems, but + // its purpose is responsiveness (a tool call mid- ещё-one-sync), not durability — the api + // server's atomic write at PUT /api/data is the source of truth, and a stale read just gets + // corrected on the next change or the next tool call. We still re-read in getState() if the + // cached state is older than the file's mtime — covers the worst case of a missed event. + try { + _watcher = fs.watch(file, () => { + // On change, simply clear the cache — the next getState() will re-read. Avoids reading + // twice if the watcher fires multiple events for one atomic-write (rename + create). + _state = undefined + _loadedMtime = 0 + }) + } catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ } +} + +/** Returns the state object (or null for a fresh account), re-reading on mtime change. */ +export function getState() { + init() + const file = stateFile(_uid) + // fs.watch's reliability varies by filesystem — we still re-read whenever the file's mtime + // has changed since our last load. This covers watcher omissions, no-watcher platforms, and + // a call landed in the brief gap between the api server's atomic write and our event firing. + let mtime + try { mtime = fs.statSync(file).mtimeMs } catch { + // File no longer exists (account deleted since boot). Return what we have if anything; + // the caller handles null/undefined same as a fresh account. + return _state === undefined ? null : _state + } + if (_state === undefined || mtime !== _loadedMtime) { + const fresh = readJsonOrNull(file) + if (fresh) { + // Same shape the frontend builds on pullState — defaults merged with stored state so any + // field the app added since the snapshot was last saved shows up undefined-safe. + _state = Object.assign({}, defaultsShape(), fresh) + _loadedMtime = mtime + } else if (_state === undefined) { + _state = null // no state file at all — never signed in on a device + } + } + return _state +} + +/** The user record (id + name) from db.json. Excludes passkeys/credentials and push subs. */ +export function getUser() { + init() + const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null } + return { id: u.id, name: u.name, created: u.created || null } +} + +/** Path to the data dir (debug/test hook). */ +export const dataDir = () => DATA_DIR + +/** + * Test-only escape hatch: work against a passed-in state object instead of reading disk. + * The MCP server is read-only, so tests don't need to write files — pass any state object + * (typically from frontend/src/lib/demoSeed.js buildDemoState()) and the tools will use it. + */ +export function _seedStateForTests(state) { + _uid = 'test-uid' + _db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] } + _state = state + _loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test + if (_watcher) { _watcher.close(); _watcher = null } +} + +/** The minimum shape the tools assume — fields default to empty/none if absent. */ +function defaultsShape() { + return { + unit: 'kg', restSec: 90, sound: true, lang: 'en', + theme: 'dark', accent: 'lime', body: 'male', targetW: null, + bodyweight: [], routines: [], week: {}, dayPlan: {}, + exWeights: {}, workouts: [], customEx: [], gifSize: 'full', + reminder: { on: false, time: '08:00', tz: null } + } +} diff --git a/mcp/src/tools.js b/mcp/src/tools.js new file mode 100644 index 0000000..df794ad --- /dev/null +++ b/mcp/src/tools.js @@ -0,0 +1,362 @@ +// The eight v1 tools — read-only views over a user's openGym state, computed by the same +// pure helpers the React UI uses (frontend/src/lib/*.js). Each handler returns JSON-shaped +// data the LLM can format as it likes; `labels.js` pre-substitutes any {0}/{1} template the +// lib returns so the LLM never re-implements the wording. +// +// Scope rules for these 8: +// • No passkey material, VAPID keys, session secrets — handlers never read or return them. +// • No raw db.json — only `getUser()` (id + name) plus the state file. +// • No in-progress ("active") workout data — the API never persists it; the file has none. +// • ISO dates validated (`YYYY-MM-DD`) so an LLM passing "yesterday" is rejected explicitly. +import { z } from 'zod' +import { getState, getUser } from './state.js' +import { + fmt, setLabel, exLine, muscleName, policyName, friendlyDate, friendlyDuration, ratio, muscleOrder +} from './labels.js' +import { + modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId +} from '../../frontend/src/lib/history.js' +import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js' +import { + estimate1RM, best1RM, e1rmSeries, FORMULAS, DEFAULT_FORMULA, REP_CAP +} from '../../frontend/src/lib/onerm.js' +import { loadOfWorkouts, rankOf, levelsOf, MUSCLES } from '../../frontend/src/lib/muscles.js' + +/* ---------- helpers ---------- */ + +const ISO = /^\d{4}-\d{2}-\d{2}$/ +function requireIso(v, name) { + const s = typeof v === 'string' ? v : '' + if (s && !ISO.test(s)) throw new Error(`${name} must be YYYY-MM-DD (got ${JSON.stringify(v)})`) + return s || null +} + +// Convert a workout entry into the JSON shape the tools expose. Everything the LLM needs to +// answer "what did I lift for X on day Y" lives here, including the mode tag and target. +function entryView(e, S) { + const ex = exOr(e.id) + const mode = modeOf(e.target || { id: e.id }) + return { + id: e.id, + name: ex.n, + body_part: ex.bp || null, + mode, + target: e.target || null, + sets: (e.sets || []).map(s => ({ + done: !!s.done, + label: setLabel(e.id, { ...s, done: undefined }, e.target || { id: e.id }), + w: Number(s.w) || 0, + r: Number(s.r) || 0, + sec: Number(s.sec) || 0, + min: Number(s.min) || 0, + speed: Number(s.speed) || 0 + })) + } +} + +// Best effort 1RM computation per exercise across a user's history. Mirrors newStats which +// powers the UI's PR table: take every eligible set across every workout and keep the biggest +// estimate per exercise, eligible = done + reps-mode + 1 <= reps <= REP_CAP (see onerm.js). +function prTable(S, formula) { + const byId = new Map() + for (const w of (S.workouts || [])) { + for (const e of (w.entries || [])) { + for (const s of (e.sets || [])) { + if (!s.done) continue + const est = estimate1RM(s.w, s.r, formula) + if (est == null) continue + const ex = exOr(e.id) + const prev = byId.get(e.id) + if (!prev || est > prev.est) { + // exId is included alongside exName because the consumer (the LLM, or our own + // estimate_1rm tool when called with one specific id) needs the id, not the name — + // exOr() falls back to treating any string as both id and name, so a caller passing + // exName where exId belongs would silently "work" against unknown exercises. + byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d }) + } + } + } + } + return [...byId.values()].sort((a, b) => b.est - a.est) +} + +/* ---------- the 8 tools ---------- */ + +/** 1. list_routines — names + counts of each routine in the user's plan. */ +export const listRoutines = { + name: 'list_routines', + description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.', + schema: {}, + handler: () => { + const S = getState() + if (!S) return noState() + return { + unit: S.unit || 'kg', + routines: (S.routines || []).map(r => ({ + id: r.id, + name: r.name, + emoji: r.emoji || null, + exercise_count: (r.ex || []).length, + superset_groups: [...new Set((r.ex || []).map(e => e.sg).filter(Boolean))].length || 0, + policy: r.policy || 'off' + })) + } + } +} + +/** 2. get_routine — the full exercise list for one routine, including set/rep targets. */ +export const getRoutine = { + name: 'get_routine', + description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.', + schema: { routine_id: z.string().min(1) }, + handler: ({ routine_id }) => { + const S = getState() + if (!S) return noState() + const r = (S.routines || []).find(x => x.id === routine_id) + if (!r) { const e = new Error(`no routine with id ${JSON.stringify(routine_id)}`); e.code = 'ENOENT'; throw e } + return { + id: r.id, + name: r.name, + emoji: r.emoji || null, + policy: r.policy || 'off', + policy_name: policyName(r.policy || 'off'), + unit: S.unit || 'kg', + exercises: (r.ex || []).map((cfg, i) => { + const ex = exOr(cfg.id) + const mode = modeOf(cfg) + return { + position: i + 1, + id: cfg.id, + name: ex.n, + body_part: ex.bp || null, + mode, + sets: cfg.sets || 1, + reps: mode === 'reps' ? (cfg.reps || 0) : undefined, + reps_min: mode === 'reps' && cfg.repsMin != null ? cfg.repsMin : undefined, + sec: mode === 'time' ? (cfg.sec || 0) : undefined, + min: mode === 'cardio' ? (cfg.min || 0) : undefined, + speed: mode === 'cardio' ? (cfg.speed || 0) : undefined, + weight: cfg.weight != null ? cfg.weight : undefined, + increment: cfg.inc != null ? cfg.inc : undefined, + policy_override: cfg.policy || null, + superset_group: cfg.sg || null, + summary: exLine(cfg, S.unit || 'kg') + } + }) + } + } +} + +/** 3. get_week_plan — what's scheduled each weekday + today. */ +export const getWeekPlan = { + name: 'get_week_plan', + description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).', + schema: {}, + handler: () => { + const S = getState() + if (!S) return noState() + const today = new Date() + const isoToday = today.getFullYear() + '-' + String(today.getMonth() + 1).padStart(2, '0') + '-' + String(today.getDate()).padStart(2, '0') + const todayWd = today.getDay() + return { + today: isoToday, + weekdays: [0, 1, 2, 3, 4, 5, 6].map(d => { + const rid = S.week?.[d] || null + const r = rid ? (S.routines || []).find(x => x.id === rid) : null + // Surface today's override only (not the whole dayPlan dict — usually empty, but might + // have grown from repeated "move this day" actions). + const overrideForToday = d === todayWd ? (S.dayPlan?.[isoToday] ?? null) : null + return { + weekday: d, + weekday_name: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d], + routine_id: rid, + routine_name: r?.name || null, + routine_emoji: r?.emoji || null, + override_for_today_or_null: overrideForToday + } + }), + today_routine_id: effectiveRoutineId(S, isoToday), + today_routine_name: effectiveRoutine(S, isoToday)?.name || null + } + } +} + +/** 4. list_workouts — newest-first summary of recent sessions. */ +export const listWorkouts = { + name: 'list_workouts', + description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.', + schema: { + from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD. Defaults to no lower bound (list most recent).'), + to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.'), + limit: z.number().int().min(1).max(200).optional().describe('Max items to return. Defaults to 25.') + }, + handler: ({ from, to, limit }) => { + const S = getState() + if (!S) return noState() + const lim = Math.min(Math.max(limit || 25, 1), 200) + const all = (S.workouts || []).slice().sort((a, b) => (b.d || '').localeCompare(a.d || '')) + const filtered = all.filter(w => { + if (from && w.d < from) return false + if (to && w.d > to) return false + return true + }).slice(0, lim) + return { + unit: S.unit || 'kg', + total_count: all.length, + returned_count: filtered.length, + workouts: filtered.map(w => ({ + date: w.d, + routine_id: w.routineId || null, + routine_name: w.name || null, + exercise_count: (w.entries || []).length, + sets_done: setsDone(w), + sets_planned: plannedSets(w), + sets_ratio: ratio(setsDone(w), plannedSets(w)), + volume: workoutVolume(w), + duration_ms: w.end && w.start ? (w.end - w.start) : null, + duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null, + prs: (w.prs || []).length, + bodyweight_at_workout: w.bw || null + })) + } + } +} + +function plannedSets(w) { + let n = 0 + ;(w.entries || []).forEach(e => { n += (e.sets || []).length }) + return n +} + +/** 5. get_workout — full entry/set breakdown for one date. */ +export const getWorkout = { + name: 'get_workout', + description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Use list_workouts first if you don\'t know the exact date.', + schema: { date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('The workout date as YYYY-MM-DD') }, + handler: ({ date }) => { + const S = getState() + if (!S) return noState() + const w = (S.workouts || []).find(x => x.d === date) + if (!w) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e } + return { + date: w.d, + routine_id: w.routineId || null, + routine_name: w.name || null, + unit: S.unit || 'kg', + bodyweight_at_workout: w.bw || null, + volume: workoutVolume(w), + sets_done: setsDone(w), + sets_planned: plannedSets(w), + duration: w.end && w.start ? friendlyDuration(w.end - w.start) : null, + prs: (w.prs || []).map(id => EXIDX[id]?.n || id), + entries: (w.entries || []).map(e => entryView(e, S)) + } + } +} + +/** 6. get_bodyweight — recent weigh-ins with the goal line. */ +export const getBodyweight = { + name: 'get_bodyweight', + description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.', + schema: { + from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive start date YYYY-MM-DD.'), + to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('Inclusive end date YYYY-MM-DD. Defaults to today.') + }, + handler: ({ from, to }) => { + const S = getState() + if (!S) return noState() + const goal = S.targetW || null + const bw = (S.bodyweight || []).filter(b => { + if (from && b.d < from) return false + if (to && b.d > to) return false + return true + }).sort((a, b) => (a.d || '').localeCompare(b.d || '')) + const latest = bw.length ? bw[bw.length - 1] : null + return { + unit: S.unit || 'kg', + goal, + count: bw.length, + latest: latest ? { date: latest.d, weight: latest.w, delta_vs_goal: goal != null ? Math.round((latest.w - goal) * 10) / 10 : null } : null, + entries: bw.map(b => ({ + date: b.d, + weight: b.w, + delta_vs_goal: goal != null ? Math.round((b.w - goal) * 10) / 10 : null + })) + } + } +} + +/** 7. estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */ +export const estimate1rm = { + name: 'estimate_1rm', + description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`, + schema: { + exercise_id: z.string().optional().describe('An exercise id from list_routines, get_workout entries, or search_exercises (v1.5). If omitted, returns a full PR table.'), + formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`) + }, + handler: ({ exercise_id, formula }) => { + const S = getState() + if (!S) return noState() + const f = formula || DEFAULT_FORMULA + if (exercise_id) { + const ex = exOr(exercise_id) + const best = best1RM(S, exercise_id, f) + const series = e1rmSeries(S, exercise_id, f) + // `w`/`r` (not `weight`/`reps`) match the field names used in pr_table and in + // get_workout's entry view — every set in the API surface uses the same couple. + return { + exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null }, + formula: f, + best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null, + trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r })) + } + } + return { + formula: f, + formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`, + pr_table: prTable(S, f) + } + } +} + +/** 8. muscle_balance — training distribution per muscle over a period (week/month/all). */ +export const muscleBalance = { + name: 'muscle_balance', + description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.', + schema: { + period: z.enum(['week', 'month', 'all']).describe('window: last 7 days, last 30 days, or all-time') + }, + handler: ({ period }) => { + const S = getState() + if (!S) return noState() + const now = Date.now() + const cutoff = period === 'week' ? now - 7 * 86400000 + : period === 'month' ? now - 30 * 86400000 + : Number.NEGATIVE_INFINITY + const workouts = (S.workouts || []).filter(w => (w.start || new Date(w.d + 'T12:00:00').getTime()) >= cutoff) + const load = loadOfWorkouts(workouts) + const { worked, missed } = rankOf(load) + const levels = levelsOf(load) + return { + period, + cutoff_iso: period === 'all' ? null : new Date(cutoff).toISOString().slice(0, 10), + workouts_in_period: workouts.length, + worked: worked.map(slug => ({ slug, name: muscleName(slug), level: levels[slug], effective_sets: Math.round((load[slug] || 0) * 10) / 10 })), + neglected: missed.map(slug => ({ slug, name: muscleName(slug) })), + muscle_order_head_to_toe: muscleOrder() + } + } +} + +/* ---------- registration list ---------- */ + +export const TOOLS = [ + listRoutines, getRoutine, getWeekPlan, listWorkouts, getWorkout, getBodyweight, estimate1rm, muscleBalance +] + +function noState() { + return { + error: 'no synced state yet — sign in at least once from a device so the openGym api can save a state file for this profile', + unit: 'kg' + } +} diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js new file mode 100644 index 0000000..9d6210d --- /dev/null +++ b/mcp/test/tools.test.js @@ -0,0 +1,474 @@ +// Tool-layer tests against the demo seed fixture (frontend/src/lib/demoSeed.js) — the same +// data the public demo deployment at https://opengym.duarte-santos.ch runs on. +// +// What this file pins (and what it doesn't): +// • The JSON shape each tool returns (fields + types) for the happy path. +// • The actual computed VALUES for a few representative cases (1RM via Epley/Brzycki, +// workoutVolume, body-weight delta). The pure lib functions have their own 92 tests in +// frontend/src/lib/*.test.js — here we only sanity-check the wiring. +// • Edge cases that are easy to silently mishandle: rest-day override, ISO-date validation, +// no-workout history, no synced state, superset linking, time/cardio mode tags. +// +// "Today" is pinned to a fixed Monday (2026-07-27) so date-dependent tools (get_week_plan, +// muscle_balance) see consistent values regardless of when the suite runs. The demo +// state is built relative to that pinned time, so internal dates (e.g. dayPlan) align. +// +// We deliberately don't test the LLM-facing JSON-RPC transport here — that's the SDK's job, +// and the smoke test in scripts/ covers the wire-level handshake. Here we call the +// handler functions directly with already-validated args. +import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest' +import { buildDemoState } from '../../frontend/src/lib/demoSeed.js' +import { _seedStateForTests } from '../src/state.js' +import { TOOLS } from '../src/tools.js' + +// Constants that originate from the lib (re-stated here so the assertions don't rely on a +//computer reading the lib to know what to expect — these are the values the demo state yields). +const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled +const GOAL_WEIGHT = 77 +const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18500, bw: 78.6, sets_done: 20, sets_total: 20, duration_min: 51 } +const LATEST_BW = { date: '2026-07-27', weight: 78.5, delta: 1.5 } +const LEG_PRESS_ID = '0739' // sled 45° leg press in the demo data +const LEG_PRESS_BEST = { w: 152.5, r: 12, epley: 213.5, brzycki: 219.6 } + +const byName = Object.fromEntries(TOOLS.map(t => [t.name, t.handler])) + +let S = null + +function call(name, params = {}) { + const h = byName[name] + if (!h) throw new Error(`unknown tool ${name}`) + return h(params) +} + +function freshState() { + const s = buildDemoState() + s.unit = 'kg' + return s +} + +// Pin "today" before building state so dayPlan/week alignment matches the assertions below. +// `toFake: ['Date']` only mocks the Date object — fs.watch / setTimeout in state.js keep +// working with the real event loop, so file watching and reaping stay untouched. +beforeAll(() => { + vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] }) + S = freshState() + _seedStateForTests(S) +}) + +afterAll(() => { + vi.useRealTimers() +}) + +// Each test sees a fresh clone of the seeded state — tests that mutate S.dayPlan (etc.) can +// never leak into a sibling test. ~1ms overhead per test, buys isolation. +beforeEach(() => { + S = freshState() + _seedStateForTests(S) +}) + +/* ---------- list_routines ---------- */ + +describe('list_routines', () => { + test('returns the three starter routines with names + counts', () => { + const r = call('list_routines') + expect(r.unit).toBe('kg') + expect(r.routines.length).toBe(3) + expect(r.routines.map(x => x.name).sort()).toEqual(['Leg Day', 'Pull Day', 'Push Day']) + r.routines.forEach(rn => { + expect(typeof rn.id).toBe('string') + expect(rn.exercise_count).toBeGreaterThan(0) + expect(typeof rn.superset_groups).toBe('number') + expect(['off', 'linear', 'greyskull', 'double', 'time']).toContain(rn.policy) + }) + }) + + test('list_routines entries line up with get_routine (no id drift)', () => { + const list = call('list_routines').routines + list.forEach(summary => { + const detail = call('get_routine', { routine_id: summary.id }) + expect(detail.id).toBe(summary.id) + expect(detail.name).toBe(summary.name) + expect(detail.exercises.length).toBe(summary.exercise_count) + }) + }) +}) + +/* ---------- get_routine ---------- */ + +describe('get_routine', () => { + test('returns the full exercise list for Push Day with per-exercise summaries', () => { + const push = call('list_routines').routines.find(x => x.name === 'Push Day') + const r = call('get_routine', { routine_id: push.id }) + expect(r.name).toBe('Push Day') + expect(r.exercises.length).toBe(push.exercise_count) + expect(r.policy_name).toBeTruthy() + r.exercises.forEach(e => { + expect(['reps', 'time', 'cardio']).toContain(e.mode) + // Every summary has "N × M" with a non-ASCII × (the lib uses U+00D7, not ASCII 'x') + expect(e.summary).toMatch(/\d+\s*×\s*\d+/) + expect(e.superset_group === null || typeof e.superset_group === 'string').toBe(true) + }) + }) + + test('throws ENOENT on a bogus routine id (does not silently return empty)', () => { + expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow() + }) + + test('reports superset links when an adjacent pair shares an sg id', () => { + // Inject a superset pair into a clone, since the starter plan has none. + S.routines[0].ex[0].sg = 'A' + S.routines[0].ex[1].sg = 'A' + const r = call('get_routine', { routine_id: S.routines[0].id }) + expect(r.exercises[0].superset_group).toBe('A') + expect(r.exercises[1].superset_group).toBe('A') + expect(r.exercises[2].superset_group).toBeNull() + }) + + test('preserves mode + per-mode fields for a timed entry and a cardio entry', () => { + // Append synthetic entries the starter plan doesn't ship: a timed plank (sec, no w) and a + // cardio treadmill block (min + speed). These exercise ids don't exist in EXDB, so exOr + // returns a placeholder named "Unknown exercise" — that's fine, we test the cfg fields. + const push = S.routines.find(r => r.name === 'Push Day') + push.ex.push({ id: 'synth-plank', sets: 3, sec: 60, weight: 0, mode: 'time' }) + push.ex.push({ id: 'synth-treadmill', sets: 1, min: 20, speed: 8, mode: 'cardio' }) + const r = call('get_routine', { routine_id: push.id }) + const t = r.exercises[r.exercises.length - 2] + const c = r.exercises[r.exercises.length - 1] + expect(t.mode).toBe('time') + expect(t.sec).toBe(60) + expect(t.reps).toBeUndefined() + expect(c.mode).toBe('cardio') + expect(c.min).toBe(20) + expect(c.speed).toBe(8) + }) +}) + +/* ---------- get_week_plan ---------- */ + +describe('get_week_plan', () => { + test('reports each weekday in getDay() order (Sunday=0 … Saturday=6) with names', () => { + const r = call('get_week_plan') + expect(r.weekdays.length).toBe(7) + expect(r.weekdays.map(d => d.weekday)).toEqual([0, 1, 2, 3, 4, 5, 6]) + expect(r.weekdays.map(d => d.weekday_name)) + .toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']) + }) + + test('today is the pinned Monday, and Push Day is scheduled', () => { + const r = call('get_week_plan') + expect(r.today).toBe(FAKE_TODAY_ISO) + const push = S.routines.find(x => x.name === 'Push Day') + expect(r.today_routine_id).toBe(push.id) + expect(r.today_routine_name).toBe('Push Day') + }) + + test('week[1]/[3]/[5] map to Push/Pull/Leg, other weekdays are rest', () => { + const r = call('get_week_plan') + const byWd = Object.fromEntries(r.weekdays.map(d => [d.weekday, d])) + expect(byWd[1].routine_name).toBe('Push Day') + expect(byWd[3].routine_name).toBe('Pull Day') + expect(byWd[5].routine_name).toBe('Leg Day') + ;[0, 2, 4, 6].forEach(wd => { + expect(byWd[wd].routine_id).toBeNull() + expect(byWd[wd].routine_name).toBeNull() + }) + }) + + test('a "rest" override on today cancels the scheduled routine', () => { + // Sanity check first — without the override, today has a routine. + const before = call('get_week_plan') + expect(before.today_routine_id).not.toBeNull() + S.dayPlan[FAKE_TODAY_ISO] = 'rest' + const after = call('get_week_plan') + expect(after.today_routine_id).toBeNull() + expect(after.today_routine_name).toBeNull() + // The override is surfaced on the matching weekday entry. + const todayWd = new Date(FAKE_TODAY_ISO + 'T12:00:00Z').getDay() + expect(after.weekdays.find(d => d.weekday === todayWd).override_for_today_or_null).toBe('rest') + }) + + test('a routine-id override on today replaces the weekday default', () => { + const legs = S.routines.find(r => r.name === 'Leg Day') + S.dayPlan[FAKE_TODAY_ISO] = legs.id + const r = call('get_week_plan') + expect(r.today_routine_id).toBe(legs.id) + expect(r.today_routine_name).toBe('Leg Day') + }) + + test('empty week + no override → today has no routine (a quiet Sunday)', () => { + S.week = {} + S.dayPlan = {} + const r = call('get_week_plan') + expect(r.today_routine_id).toBeNull() + expect(r.today_routine_name).toBeNull() + r.weekdays.forEach(d => expect(d.routine_id).toBeNull()) + }) +}) + +/* ---------- list_workouts ---------- */ + +describe('list_workouts', () => { + test('newest first, with computed volume/duration matching hand-calculated values', () => { + const r = call('list_workouts', {}) + expect(r.returned_count).toBeGreaterThan(0) + expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count) + // newest-first check + const dates = r.workouts.map(w => w.date) + expect([...dates].sort().reverse()).toEqual(dates) + // The newest workout is the Friday before the pinned Monday today. + expect(r.workouts[0].date).toBe(NEWEST_WORKOUT.date) + expect(r.workouts[0].routine_name).toBe(NEWEST_WORKOUT.name) + expect(r.workouts[0].volume).toBe(NEWEST_WORKOUT.volume) + expect(r.workouts[0].sets_done).toBe(NEWEST_WORKOUT.sets_done) + expect(r.workouts[0].sets_planned).toBe(NEWEST_WORKOUT.sets_total) + expect(r.workouts[0].sets_ratio).toBe(`${NEWEST_WORKOUT.sets_done}/${NEWEST_WORKOUT.sets_total}`) + expect(r.workouts[0].duration).toBe(`${NEWEST_WORKOUT.duration_min} min`) + expect(r.workouts[0].bodyweight_at_workout).toBe(NEWEST_WORKOUT.bw) + r.workouts.forEach(w => { + expect(w.sets_done).toBeLessThanOrEqual(w.sets_planned) + expect(typeof w.volume).toBe('number') + expect(w.sets_ratio).toMatch(/^\d+\/\d+$/) + }) + }) + + test('date range filter narrows results (closed interval, both endpoints inclusive)', () => { + const all = call('list_workouts') + expect(all.workouts.length).toBeGreaterThan(2) + const earliest = all.workouts[all.workouts.length - 1].date + // closed on both ends — earliest's own date should still appear + const restricted = call('list_workouts', { from: earliest, to: earliest }) + expect(restricted.returned_count).toBe(1) + expect(restricted.workouts[0].date).toBe(earliest) + }) + + test('a from > to range yields zero workouts (not an error, not silently everything)', () => { + const r = call('list_workouts', { from: '2026-07-27', to: '2026-01-01' }) + expect(r.returned_count).toBe(0) + expect(r.workouts).toEqual([]) + expect(r.total_count).toBeGreaterThan(0) // total still reflects the real history + }) + + test('respects limit (caps returned_count, never total_count)', () => { + const r = call('list_workouts', { limit: 3 }) + expect(r.returned_count).toBeLessThanOrEqual(3) + expect(r.total_count).toBeGreaterThanOrEqual(r.returned_count) + }) +}) + +/* ---------- get_workout ---------- */ + +describe('get_workout', () => { + test('matches the newest workout from list_workouts, every set has a readable label', () => { + const list = call('list_workouts', {}).workouts + const w = call('get_workout', { date: list[0].date }) + expect(w.date).toBe(list[0].date) + expect(w.entries.length).toBe(list[0].exercise_count) + expect(w.volume).toBe(list[0].volume) + w.entries.forEach(e => { + expect(['reps', 'time', 'cardio']).toContain(e.mode) + e.sets.forEach(s => { + expect(typeof s.label).toBe('string') + expect(s.label.length).toBeGreaterThan(0) + }) + }) + }) + + test('throws ENOENT on a date with no workout', () => { + expect(() => call('get_workout', { date: '1900-01-01' })).toThrow() + }) + + test('renders reps/time/cardio set labels in the lib format on a synthetic workout', () => { + // The starter routine has only reps-mode exercises — synthesise a workout that includes a + // timed plank and a cardio row so the label rendering is actually exercised. + S.workouts = [{ + id: 'synth-1', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth', + bw: 78, vol: 0, prs: [], + entries: [ + { id: 'squat', target: { mode: 'reps' }, sets: [{ w: 60, r: 5, done: true }] }, + { id: 'plank', target: { mode: 'time' }, sets: [{ sec: 90, w: 0, done: true }] }, + { id: 'plank-w', target: { mode: 'time' }, sets: [{ sec: 90, w: 20, done: true }] }, + { id: 'row', target: { mode: 'cardio' }, sets: [{ min: 20, speed: 8, done: true }] } + ] + }] + const w = call('get_workout', { date: '2026-07-25' }) + expect(w.entries[0].sets[0].label).toBe('60×5') // reps + // 90 sec → 1 min 30 sec → mm:ss label is "1:30" (fmtSec in history.js) + expect(w.entries[1].sets[0].label).toBe('1:30') // 90 s in mm:ss, no weight + expect(w.entries[2].sets[0].label).toBe('1:30 · 20') // weighted plank + expect(w.entries[3].sets[0].label).toBe('20 min @ 8 km/h') // cardio + }) +}) + +/* ---------- get_bodyweight ---------- */ + +describe('get_bodyweight', () => { + test('returns weigh-ins with the goal, the latest entry, and exact delta vs goal', () => { + const r = call('get_bodyweight') + expect(r.goal).toBe(GOAL_WEIGHT) + expect(r.entries.length).toBeGreaterThan(0) + // Newest is the LATEST_BW entry (deterministic from the demo seed at the pinned time). + expect(r.latest).toBeTruthy() + expect(r.latest.date).toBe(LATEST_BW.date) + expect(r.latest.weight).toBe(LATEST_BW.weight) + expect(r.latest.delta_vs_goal).toBe(LATEST_BW.delta) + // entries are chronological + const dates = r.entries.map(e => e.date) + expect([...dates].sort()).toEqual(dates) + }) + + test('closed date range returns a single matching entry on the boundary', () => { + const all = call('get_bodyweight') + expect(all.entries.length).toBeGreaterThan(1) + const earliest = all.entries[0].date + const restricted = call('get_bodyweight', { from: earliest, to: earliest }) + expect(restricted.entries.length).toBe(1) + expect(restricted.entries[0].date).toBe(earliest) + }) + + test('no goal set → delta_vs_goal is null, not NaN, not zero', () => { + S.targetW = null + const r = call('get_bodyweight') + expect(r.goal).toBeNull() + r.entries.forEach(e => expect(e.delta_vs_goal).toBeNull()) + expect(r.latest.delta_vs_goal).toBeNull() + }) +}) + +/* ---------- estimate_1rm ---------- */ + +describe('estimate_1rm', () => { + test('PR table across all reps-mode exercises; epley formula is the default', () => { + const r = call('estimate_1rm', {}) + expect(r.formula).toBe('epley') + expect(Array.isArray(r.pr_table)).toBe(true) + expect(r.pr_table.length).toBeGreaterThan(0) + r.pr_table.forEach(p => { + expect(typeof p.est).toBe('number') + expect(p.est).toBeGreaterThan(0) + expect(typeof p.exName).toBe('string') + expect(typeof p.exId).toBe('string') // exId surfaced (regression test for the bug where callers passed exName as id) + }) + // sort order: descending by est + for (let i = 1; i < r.pr_table.length; i++) { + expect(r.pr_table[i].est).toBeLessThanOrEqual(r.pr_table[i - 1].est) + } + }) + + test('top-of-table values exactly match the hand-computed Epley for the demo seed', () => { + const r = call('estimate_1rm', {}) + const top = r.pr_table[0] + // Demo seed's hardest set: sled 45° leg press at 152.5×12 (r=12 hits estimate1RM's REP_CAP). + expect(top.exId).toBe(LEG_PRESS_ID) + expect(top.w).toBe(LEG_PRESS_BEST.w) + expect(top.r).toBe(LEG_PRESS_BEST.r) + expect(top.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1) + }) + + test('per-exercise trend + best, with formula honours (Epley vs Brzycki numbers diverge)', () => { + const epley = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'epley' }) + expect(epley.exercise.id).toBe(LEG_PRESS_ID) + expect(epley.formula).toBe('epley') + expect(Array.isArray(epley.trend)).toBe(true) + expect(epley.best).toBeTruthy() + expect(epley.best.w).toBe(LEG_PRESS_BEST.w) + expect(epley.best.r).toBe(LEG_PRESS_BEST.r) + expect(epley.best.est).toBeCloseTo(LEG_PRESS_BEST.epley, 1) + const brz = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: 'brzycki' }) + expect(brz.formula).toBe('brzycki') + expect(brz.best.est).toBeCloseTo(LEG_PRESS_BEST.brzycki, 1) + // Distinct formulas must produce distinct estimates for this set. + expect(epley.best.est).not.toBeCloseTo(brz.best.est, 1) + }) + + test('exercises with no reps-mode history get null best + empty trend (not a 0 estimate)', () => { + S.workouts = [] + const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID }) + expect(r.best).toBeNull() + expect(r.trend).toEqual([]) + const table = call('estimate_1rm', {}).pr_table + expect(table).toEqual([]) + }) + + test('all three formulas are accepted', () => { + ['epley', 'brzycki', 'lombardi'].forEach(f => { + const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: f }) + expect(r.formula).toBe(f) + expect(r.best).not.toBeNull() + }) + }) +}) + +/* ---------- muscle_balance ---------- */ + +describe('muscle_balance', () => { + test('reports worked + neglected muscles in head-to-toe order over all time', () => { + const r = call('muscle_balance', { period: 'all' }) + expect(r.period).toBe('all') + expect(r.workouts_in_period).toBeGreaterThan(0) + expect(Array.isArray(r.worked)).toBe(true) + expect(Array.isArray(r.neglected)).toBe(true) + expect(r.muscle_order_head_to_toe[0]).toBe('trapezius') + expect(r.muscle_order_head_to_toe.at(-1)).toBe('tibialis') + r.worked.forEach(w => { + expect(w.level).toBeGreaterThanOrEqual(1) + expect(w.level).toBeLessThanOrEqual(4) + expect(typeof w.name).toBe('string') + expect(typeof w.effective_sets).toBe('number') + }) + }) + + test('worked + neglected partition every muscle exactly once', () => { + const r = call('muscle_balance', { period: 'all' }) + const all = new Set(r.muscle_order_head_to_toe) + const worked = new Set(r.worked.map(w => w.slug)) + const neg = new Set(r.neglected.map(n => n.slug)) + expect(worked.size + neg.size).toBe(all.size) + expect([...worked].every(s => all.has(s))).toBe(true) + expect([...neg].every(s => all.has(s))).toBe(true) + }) + + test('period windows are inclusive: week ≤ month ≤ all', () => { + const all = call('muscle_balance', { period: 'all' }).workouts_in_period + const month = call('muscle_balance', { period: 'month' }).workouts_in_period + const week = call('muscle_balance', { period: 'week' }).workouts_in_period + expect(week).toBeLessThanOrEqual(month) + expect(month).toBeLessThanOrEqual(all) + }) + + test('zero-workout state still returns all 18 muscles as neglected (not empty)', () => { + S.workouts = [] + const r = call('muscle_balance', { period: 'all' }) + expect(r.workouts_in_period).toBe(0) + expect(r.worked).toEqual([]) + expect(r.neglected.length).toBe(r.muscle_order_head_to_toe.length) + expect(r.neglected.length).toBe(18) + }) +}) + +/* ---------- shared: no-state fallback ---------- */ + +describe('shared: no-state fallback', () => { + test('every tool answers gracefully when state is null (fresh account, never signed in)', () => { + _seedStateForTests(null) + // Each tool gets the minimum args its zod schema mandates; under real LLM-client use the + // SDK rejects missing ones before the handler runs, so we only test the post-validation path. + const calls = { + list_routines: {}, + get_routine: { routine_id: '0031' }, + get_week_plan: {}, + list_workouts: {}, + get_workout: { date: '2026-07-26' }, + get_bodyweight: {}, + estimate_1rm: {}, + muscle_balance: { period: 'all' } + } + for (const t of TOOLS) { + const r = t.handler(calls[t.name] || {}) + expect(r).toHaveProperty('error') + } + }) + + // Restore state after the no-state detour so a future test that forgets to seed sees the + // failure rather than inherits null silently. + afterAll(() => { _seedStateForTests(S = freshState()) }) +}) diff --git a/mcp/vitest.config.js b/mcp/vitest.config.js new file mode 100644 index 0000000..19d1b06 --- /dev/null +++ b/mcp/vitest.config.js @@ -0,0 +1,21 @@ +// Vitest config for the MCP server tool tests. Mirrors the conventions of frontend/vite.config.js +// (no global config, no auto-watch, run once and exit) — kept in mcp/ rather than hoisted to the +// repo root so this package is self-contained and re-usable for any Node-side helper we add later. +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + include: ['test/**/*.test.js'], + // The tests import from ../src and ../../frontend/src/lib, both already ESM — no transform + // needed beyond what Vite does natively. Fake timers are used in tests that pin "today" + // (see tools.test.js header comment); they only mock Date, not setTimeout, so the file + // watcher in state.js (real setTimeout/setInterval via fs.watch) keeps working. + globals: false, + environment: 'node', + pool: 'forks', + // Stryker spawns vitest per-mutant; isolating each test file in its own process keeps a + // crashing mutant from taking siblings down with it. Costs ~50ms/test, trade worth it. + isolate: true, + reporters: ['default'] + } +}) From 4143ab8676eeb33fda9e2c6cbbdcdd1b284c5ea4 Mon Sep 17 00:00:00 2001 From: Pengboi Date: Sun, 26 Jul 2026 19:34:15 +0100 Subject: [PATCH 03/58] Tests: Stryker mutation testing on the MCP handlers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Stryker 9.6.1 as a devDep and a .stryker.conf.json scoped to the three MCP-only modules (src/state.js, src/labels.js, src/tools.js). The reused pure lib in frontend/src/lib/ is deliberately excluded — it has its own 92-test vitest suite, and mutating it here would just re-test it under a different label. Two non-obvious config choices, both learned the hard way: · inPlace: true. Stryker's default copies the project to a sandbox, but the MCP test file imports "../../frontend/src/lib/*.js" — a relative path that breaks the moment the source is moved. inPlace mutates files where they live, keeps a backup in .stryker-tmp/backup-*/ during the run, and restores on exit. Verified: after the run, `git diff` shows no changes and all 92+32 tests still pass. · vitest.related: false. The vitest runner's related-files mode uses static import analysis to pick which tests to run per mutant; it can't see the cross-directory imports and reported "no tests were found". Disabling it means every mutant runs the full suite — slower (~54s for 847 mutants) but accurate. Baseline first run: 39.32% mutation score (333 killed, 330 survived, 184 no-coverage). Most of the survivors are zod schema string literals (the unit suite bypasses the SDK's validation by calling handlers directly), and the bulk of the no-coverage debt lives in state.js — file watching, multi-user resolution and the mtime fallback paths. The HTML report at mcp/reports/mutation/mutation.html (gitignored, regenerated per run) shows each survived mutant inline. Run with `npm run mutation:test` from mcp/. --- .gitignore | 5 +++++ mcp/.stryker.conf.json | 29 +++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 mcp/.stryker.conf.json diff --git a/.gitignore b/.gitignore index 12881fa..ff8dc43 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,8 @@ frontend/dist/ node_modules/ *.log .DS_Store + +# Mutation-testing artifacts (mcp/) — reports/ is the HTML output, .stryker-tmp/ holds the +# backing copy used by `inPlace` mode during a run. Both regenerated on every `stryker run`. +mcp/reports/ +mcp/.stryker-tmp/ diff --git a/mcp/.stryker.conf.json b/mcp/.stryker.conf.json new file mode 100644 index 0000000..a564d45 --- /dev/null +++ b/mcp/.stryker.conf.json @@ -0,0 +1,29 @@ +{ + "$schema": "./node_modules/@stryker-mutator/core/schema/stryker-schema.json", + "packageManager": "npm", + "testRunner": "vitest", + "vitest": { + "configFile": "vitest.config.js", + "related": false + }, + "coverageAnalysis": "perTest", + "mutate": [ + "src/state.js", + "src/labels.js", + "src/tools.js" + ], + "testFiles": [ + "test/**/*.test.js" + ], + "inPlace": true, + "ignorePatterns": [], + "thresholds": { + "high": 80, + "low": 60, + "break": 0 + }, + "reporters": ["html", "progress", "clear-text"], + "concurrency": 2, + "disableTypeChecks": true, + "cleanTempDir": true +} From 6aaf2a3eea9ed147c6257ca88499d000396f2308 Mon Sep 17 00:00:00 2001 From: Pengboi Date: Sun, 26 Jul 2026 19:47:52 +0100 Subject: [PATCH 04/58] Comments: trim to the established cadence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The MCP code came in with 5–8 line file headers, JSDoc on every one-line wrapper, and inline explanations that referenced the PR itself ("so the MCP server can reuse it") — none of which matches api/server.js or frontend/src/lib/, where comments are one-line, fact-shaped and never mention the change that introduced them. Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js, format.js, mcp/test/tools.test.js, mcp/vitest.config.js and mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch rationale folded into one; the ASCII import diagram in the README replaced with a paragraph; the cross-references and self-references removed. Also fixed two real defects: a corrupted Cyrillic word in a state.js comment and a missing space in a tools.test.js comment. No code changes; 92 frontend + 32 MCP tests still pass. --- frontend/src/lib/exercises.js | 4 +- frontend/src/lib/format.js | 2 - frontend/src/lib/i18n-core.js | 34 ++++--------- frontend/src/lib/i18n.js | 15 ++---- mcp/README.md | 89 ++++++++++------------------------- mcp/src/index.js | 29 ++++-------- mcp/src/labels.js | 18 ++----- mcp/src/state.js | 59 +++++++---------------- mcp/src/tools.js | 45 +++++++----------- mcp/test/tools.test.js | 34 ++++--------- mcp/vitest.config.js | 9 ---- 11 files changed, 93 insertions(+), 245 deletions(-) diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index 451929f..a16443f 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -1,6 +1,4 @@ import { EXDB } from './exercises-data.js' -// Imports i18n-core (not i18n.js) so this stays loadable from plain Node — the MCP server -// reuses EXIDX/musclesOf/etc. without dragging in the React + Vite-only i18n.js. import { t } from './i18n-core.js' export { EXDB } @@ -31,7 +29,7 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB] // Media normally sits next to the app (img/ and gif/, mounted into the web container). // A build can point them somewhere else — the demo build pulls them off a CDN instead of // shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain -// Node; guard with `?.` so this module is loadable from Node without Vite (see i18n-core.js). +// Node; the guard keeps this module loadable without Vite. const ENV = import.meta.env || {} const IMG_BASE = ENV.VITE_IMG_BASE || 'img/' const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/' diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js index 8eb4a46..e8eadeb 100644 --- a/frontend/src/lib/format.js +++ b/frontend/src/lib/format.js @@ -1,6 +1,4 @@ // Formatting + date helpers (ported from the vanilla app, unit taken from the store where needed). -// Imports i18n-core (not i18n.js) so this pure helper stays loadable from plain Node — that's -// what lets the MCP server reuse it instead of reimplementing number/date formatting. import { dateLocale, t } from './i18n-core.js' export const todayISO = () => { const d = new Date() diff --git a/frontend/src/lib/i18n-core.js b/frontend/src/lib/i18n-core.js index 7bc5447..cfa4924 100644 --- a/frontend/src/lib/i18n-core.js +++ b/frontend/src/lib/i18n-core.js @@ -1,13 +1,6 @@ -// Pure, runtime-agnostic core of the i18n module. -// -// Split out of i18n.js so the pure-function training helpers (format.js, exercises.js and -// everything they import transitively — history, progression, onerm, muscles, demoSeed) can -// be required from plain Node too. That reuse is what lets the MCP server compute 1RM, muscle -// balance and progression prescriptions without re-implementing them — the same code that -// produces the numbers shown in the UI produces the numbers an LLM answers with. -// -// Everything browser-specific (React subscription hook, Vite's import.meta.glob lazy-loads of -// locale packs) stays in i18n.js, which re-exports these readers verbatim. +// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale, +// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy +// loads, the React subscription hook) live in i18n.js and re-export from here. export const LANGS = { en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano', @@ -20,12 +13,10 @@ export const DATE_LOCALES = { pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN' } -// Mutable module state. `lang`/`dict`/`instr` are the readers' inputs; the browser-side -// `setLang` (in i18n.js) is the only writer, so they stay private to this module. -let lang = 'en' -let dict = {} -let instr = null // { exId: [steps] } for the current language, null = English -let version = 0 +let lang = 'en' // set only by _setLangState, called from i18n.js setLang +let dict = {} // current locale pack (empty = English fallback) +let instr = null // { exId: [steps] } for the current language, null = English +let version = 0 // bumped on every setLang; drives the React subscription selector export const getLang = () => lang export const dateLocale = () => DATE_LOCALES[lang] || 'en-GB' @@ -41,14 +32,9 @@ export function t(s, ...args) { // Instructions for an exercise in the current language (English steps as fallback). export const instrFor = ex => (instr && instr[ex.id]) || ex.st || [] -/** - * Internal setter invoked by i18n.js's `setLang` once the locale pack has been loaded. - * Kept here — rather than just exported as `setLang` — because loading packs requires - * Vite's `import.meta.glob`, which would drag this file straight back into not being - * Node-safe. Returns the new version so the caller can notify its React subscribers. - * - * Both `dict` and `instr` may be passed as `null` to reset to English. - */ +// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than +// exported as setLang because loading packs requires import.meta.glob, which is Vite-only. +// Both `dict` and `instr` may be null to reset to English. export function _setLangState(newLang, newDict, newInstr) { lang = LANGS[newLang] ? newLang : 'en' dict = lang === 'en' ? {} : (newDict || {}) diff --git a/frontend/src/lib/i18n.js b/frontend/src/lib/i18n.js index 498eadc..12ead1f 100644 --- a/frontend/src/lib/i18n.js +++ b/frontend/src/lib/i18n.js @@ -1,10 +1,7 @@ -// Browser-only shell of the i18n module. -// -// Pure state, constants and readers (t, dateLocale, instrFor, getLang, LANGS, INSTR_LANGS) -// live in i18n-core.js so plain Node can reuse the training logic without a Vite environment. -// This file adds the two pieces that genuinely need the browser: the async `setLang` (which -// lazy-loads locale packs via import.meta.glob) and the React subscription hook `useLang` -// (which re-renders components on language switch). +// Browser-only shell of the i18n module. The runtime-agnostic state and readers live +// in i18n-core.js (plain Node-loadable); this file adds the two pieces that genuinely need +// the browser: `setLang` (which lazy-loads locale packs via import.meta.glob) and the React +// subscription hook `useLang`. import { useSyncExternalStore } from 'react' import { @@ -12,8 +9,6 @@ import { getLang, dateLocale, t, instrFor, getVersion, _setLangState } from './i18n-core.js' -// Re-export everything verbatim so existing callers (`import { t } from '../lib/i18n.js'`) -// keep working unchanged — the split is invisible at the import site. export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor } // Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use @@ -27,8 +22,6 @@ const notify = () => { subs.forEach(f => f()) } export async function setLang(l) { if (!LANGS[l]) l = 'en' - // _setLangState mutates core state and bumps the version; we read it back for the - // subscription selector below. if (l === getLang() && getVersion() > 0) return let dict = {}, instr = null try { diff --git a/mcp/README.md b/mcp/README.md index 66d7d9e..9007e0e 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -86,35 +86,25 @@ re-interpret them. ## How it reuses the training logic -openGym deliberately keeps its training logic in pure functions under `frontend/src/lib/` with -unit tests next to them (see `CONTRIBUTING.md` — "Training logic gets a unit test"). The MCP -server imports those files directly as Node ESM and calls the same functions the UI does: +The MCP server imports the training helpers under `frontend/src/lib/` directly as Node ESM +and calls the same functions the React UI does (`history.js`, `onerm.js`, `muscles.js`, +`exercises.js`). The numbers it returns match what the Stats screen shows, because they are +the same code. -``` -mcp/src/tools.js - └── list_workouts handler ──▶ frontend/src/lib/history.js (workoutVolume, setsDone) - └── estimate_1rm handler ──▶ frontend/src/lib/onerm.js (best1RM, e1rmSeries) - └── muscle_balance ──▶ frontend/src/lib/muscles.js (loadOfWorkouts, rankOf, levelsOf) - └── get_week_plan ──▶ frontend/src/lib/history.js (effectiveRoutine, effectiveRoutineId) -``` - -The one lib file that wasn't Node-safe was `i18n.js` (it used Vite's `import.meta.glob`) -— split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React-specific bits, re-exports -from core). `exercises.js` got a one-line guard against `import.meta.env` being undefined in -plain Node. No new dependencies landed in `frontend/`, no public exports changed. +The one lib file that wasn't Node-safe was `i18n.js` (Vite's `import.meta.glob` at module +top level) — split into `i18n-core.js` (pure, Node-safe) + `i18n.js` (Vite/React bits, +re-exports from core). `exercises.js` got a one-line `import.meta.env || {}` guard. No new +dependencies landed in `frontend/`, no public exports changed. ## Design constraints honoured -- **One runtime dependency beyond the MCP SDK:** none. `mcp/package.json` declares only - `@modelcontextprotocol/sdk` + its transitive `zod`. No database driver, no HTTP framework. +- **One runtime dependency beyond the MCP SDK:** none. No database driver, no HTTP framework. - **No new container.** stdio transport is spawned by the LLM client; nothing to add to `docker-compose.yml`. - **No new auth.** The filesystem is the boundary — same as `docker compose` running on the - user's box. The MCP server only sees what its host process can already see. + user's box. No passkey material, VAPID keys, or session secrets ever cross it. - **No telemetry, no network.** Reads `./data/*.json` and exits when the LLM client - disconnects. Matches the openGym ethos from `README.md`. -- **State-On-Disk source of truth.** Uses `fs.watch` to pick up sessions the web UI just - finished, with an mtime fallback for platforms where watchers are flaky. + disconnects. ## Tests @@ -122,21 +112,12 @@ plain Node. No new dependencies landed in `frontend/`, no public exports changed cd mcp && npm test ``` -Tool-layer tests (32 of them) seed state from `frontend/src/lib/demoSeed.js` — the same -deterministic fixture the public demo deployment runs on. The pure lib functions themselves -already have 92 tests of their own in `frontend/src/lib/*.test.js`. - -Three things the suite is deliberate about: -- **Pinned fake time.** `vi.useFakeTimers({ now: new Date('2026-07-27T12:00:00Z'), toFake: - ['Date'] })` freezes "today" to a Monday so date-dependent tools (`get_week_plan`, - `muscle_balance`) see consistent values. `toFake: ['Date']` only mocks the Date object — - `fs.watch`, `setTimeout` etc. keep working with the real event loop. -- **Real numeric assertions** for a representative case per tool: hand-computed Epley 1RM - (`152.5×12 → 213.5`), hand-computed body-weight delta (`78.5 − 77 = 1.5`), exact workout - volume (`18500` kg). Structure-only assertions ("est > 0") are kept for the cases where the - pure lib has its own tests already. -- **Negative cases.** Empty state, missing routine, missing workout, reversed date range, - no goal set, zero-workout `muscle_balance`, fresh-account no-state fallback for every tool. +32 cases seeding state from `frontend/src/lib/demoSeed.js` (the same deterministic fixture +the public demo runs on). Pins JSON shape and the user-facing edge cases: rest-day override, +missing routine, zero-workout history, no synced state, superset links, three 1RM formulas. +"Today" is pinned via `vi.useFakeTimers({ now: ..., toFake: ['Date'] })` so date-dependent +tools see consistent values regardless of when the suite runs. The pure lib functions have +their own 92 tests in `frontend/src/lib/*.test.js`. ## Mutation testing @@ -144,34 +125,16 @@ Three things the suite is deliberate about: cd mcp && npm run mutation:test ``` -Uses [Stryker](https://stryker-mutator.io) to mutate `src/state.js`, `src/labels.js` and -`src/tools.js` (the three MCP-only modules — the reused pure lib in `frontend/src/lib/` is -excluded since it has its own 92-test vitest suite). Config lives at `.stryker.conf.json`. +[Stryker](https://stryker-mutator.io) 9.6.1 against the three MCP-only modules in `src/` +(`frontend/src/lib/` is excluded — it has its own 92-test suite). Config at +`.stryker.conf.json`. Run uses `inPlace: true` so the test file's relative imports +`../../frontend/src/lib/*.js` keep resolving; Stryker keeps a backup in `.stryker-tmp/` +during the run and restores on exit. -**Run mode:** `inPlace: true`. Stryker mutates files where they live (so the test file's -relative imports `../../frontend/src/lib/*.js` keep resolving), keeps a backup in -`.stryker-tmp/backup-*/` during the run, and restores on exit — verified: after the run, -`git diff` shows no changes and all tests still pass. If Stryker is killed hard (SIGKILL, -power loss) the next run restores from the backup before mutating again. - -**Baseline (first run, 847 mutants):** - -| File | Score | Killed | Survived | No cov | -|---|---:|---:|---:|---:| -| `state.js` | 3.92% | 6 | 26 | 121 | -| `labels.js` | 23.64% | 13 | 25 | 17 | -| `tools.js` | 49.14% | 314 | 279 | 46 | -| **Total** | **39.32%** | 333 | 330 | 184 | - -The 39% baseline is honest about how much of the *handler* logic the test suite genuinely -exercises — many of the survivors are zod schema declarations (e.g. `period: -z.enum(['week', 'month', 'all'])`) which mutation-testing finds hard to kill without testing -the SDK's validation layer that the unit suite deliberately bypasses. Treat the score as a -lower bound: every "no cov" mutant is a code path the suite hasn't even reached; each is a -TODO on its own. Iterate; aim for 70%+ before the MCP server moves from v0.1 to v1. - -Report at `mcp/reports/mutation/mutation.html` (open in a browser, click any file to see -survived mutants inline). +Baseline: 39% mutation score (333 killed / 330 survived / 184 no-coverage). Most of the +survivors are zod schema string literals; the bulk of the no-coverage debt lives in +`state.js` (file watching, multi-user resolution, mtime fallback). HTML report at +`mcp/reports/mutation/mutation.html` (gitignored, regenerated per run). ## Roadmap diff --git a/mcp/src/index.js b/mcp/src/index.js index 9ef03a1..6c1ff35 100644 --- a/mcp/src/index.js +++ b/mcp/src/index.js @@ -1,15 +1,7 @@ #!/usr/bin/env node -// openGym MCP server — stdio transport, read-only tools over a single user's state file. -// -// Spawning model (per the official MCP design): the LLM client (Claude Desktop, Cursor, -// Cline, …) starts this process locally, talks JSON-RPC over stdin/stdout, and tears it down -// when the session ends. That matches openGym's "your data stays in a folder you control" -// ethos — no extra container, no new outbound network, no third-party service. -// -// Env: -// OPENGYM_DATA directory containing db.json + state-.json (default: ./data) -// OPENGYM_UID which profile to answer for (default: auto-detect the single-user case) -// OPENGYM_LANG reserved for future label-localisation (default: en) +/* openGym MCP server — stdio transport. The LLM client (Claude Desktop, Cursor, …) spawns + this process locally, talks JSON-RPC over stdin/stdout, tears it down when the session ends. + No extra container, no new outbound network — your data stays in a folder you control. */ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' import { TOOLS } from './tools.js' @@ -20,22 +12,17 @@ const server = new McpServer({ version: '0.1.0' }) -// Initialise the state view up-front so a bad config (missing data dir, ambiguous uid) fails -// fast with a clear message on stderr rather than silently answering every tool call with the -// "no synced state" fallback. init() is idempotent — the LLM client restart is cheap. +// Fail fast on bad config so a misnamed OPENGYM_DATA doesn't silently answer every call with +// the no-state sentinel. Always register every tool so the LLM sees the full list at +// handshake, even when state didn't resolve. try { init() - // Always register every tool, regardless of whether state resolved — an LLM client that - // learns the tool list at handshake should see all eight. The handlers themselves degrade - // gracefully if state is null (returns the no-state sentinel object). const u = getUser() console.error(`[opengym-mcp] serving profile ${u.name} (${u.id})`) } catch (e) { console.error(`[opengym-mcp] ${e.message}`) - // Don't exit — keep the server up so the LLM client still gets tool listings and a useful - // error if it tries to call one. Most issues are env-shaped (wrong OPENGYM_DATA path) and - // a user will restart once they fix it; failing at handshake is more annoying than a clear - // runtime error. + // Don't exit — keep the tool listings up so the user sees a useful error after fixing their + // env and restarting. } for (const t of TOOLS) { diff --git a/mcp/src/labels.js b/mcp/src/labels.js index 6462382..f65e162 100644 --- a/mcp/src/labels.js +++ b/mcp/src/labels.js @@ -1,25 +1,19 @@ -// Formatting glue between pure lib helpers and the JSON the MCP tools return to an LLM. -// -// The lib modules speak in compact codes (e.g. `nextPrescription.why` is [template, ...args]) -// because the UI also needs to translate them. An LLM doesn't read templates, so the tools -// format each value into final English text before serialising. Keeping this in one place -// means a fix to a phrasing lands in every tool at once. +// Formatting glue between lib helpers (which speak {0}/{1} templates) and the JSON returned +// to the LLM. import { MUSCLE_NAME, MUSCLES } from '../../frontend/src/lib/muscles.js' import { modeOf, fmtSec, setLabel } from '../../frontend/src/lib/history.js' import { POLICY_NAME } from '../../frontend/src/lib/progression.js' import { fmtDate, fmtNum, fmtDur } from '../../frontend/src/lib/format.js' -/** Apply {0},{1},… substitutions to the template strings the lib returns. */ +// Apply {0},{1},… substitutions to the template strings the lib returns. export function fmt(template, args) { let v = template for (let i = 0; i < (args || []).length; i++) v = v.replaceAll('{' + i + '}', String(args[i])) return v } -/** Pre-formatted label for one set, e.g. "5 @ 60 kg", "1:30 · 20 kg", "20 min @ 8 km/h". */ export { setLabel } -/** A one-line description of a routine entry, e.g. "3 × 10 · 60 kg". Accepts a cfg + unit. */ export function exLine(cfg, unit) { const mode = modeOf(cfg) const n = cfg.sets || 1 @@ -29,31 +23,25 @@ export function exLine(cfg, unit) { return `${n} × ${cfg.reps}${load}` } -/** A human name for a muscle slug, falling back to the slug if unmapped. */ export function muscleName(slug) { return MUSCLE_NAME[slug] || slug } -/** English name of a progression policy, falling back to the slug. */ export function policyName(policy) { return POLICY_NAME[policy] || policy } -/** Friendly month-day for an ISO date ("3 Jul"); used in summaries so the LLM reads natural. */ export function friendlyDate(iso) { if (!iso) return null return fmtDate(iso) } -/** Duration in minutes ("46 min", "1h 14m"). */ export function friendlyDuration(ms) { return ms ? fmtDur(ms) : null } -/** Sums vs planned and returns a "{done}/{total}" label. */ export function ratio(done, total) { return `${done}/${total}` } -/** Returns the muscle slugs in head-to-toe order (the same order UI lists them). */ export function muscleOrder() { return MUSCLES.slice() } diff --git a/mcp/src/state.js b/mcp/src/state.js index 8ce0c6e..bf26a2d 100644 --- a/mcp/src/state.js +++ b/mcp/src/state.js @@ -1,24 +1,18 @@ -// State accessor — opens ./data/state-.json (+ db.json for the user record), caches it, -// and re-reads via fs.watch so tools reflect a session the web UI just finished without a -// server restart. Read-only by design: nothing in the MCP server ever writes to these files, -// which keeps it consistent with the api server's own read-on-write view of state. -// -// The state shape comes straight from frontend/src/store/useStore.js DEF; the runtime fields -// that stay device-local (`active`) never reach the file — see api server.js PUT /api/data. +/* opengym-mcp state — reads ./data/state-.json + db.json (read-only). Cached with an + fs.watch + mtime fallback so a session the api server just wrote is visible on the next + tool call without a restart. */ import fs from 'node:fs' import path from 'node:path' const DATA_DIR = process.env.OPENGYM_DATA || path.join(process.cwd(), 'data') -// Cached state. `null` means "no state file for this user" (e.g. brand-new account that never -// signed in on a device). `undefined` means "not yet loaded". +// null = no state file (brand-new account); undefined = not yet loaded. let _state = undefined let _db = undefined let _uid = null let _watcher = null let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions -/** A safe read of a JSON file; returns null on missing/invalid rather than throwing. */ function readJsonOrNull(file) { try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null } } @@ -29,18 +23,9 @@ function stateFile(uid) { return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json') } -/** - * Resolve which user the MCP server should answer for. - * - * Strategy, in order: - * 1. OPENGYM_UID env — explicit choice on multi-user instances. - * 2. Exactly one state file in ./data — the common self-hosted single-user case. - * 3. Exactly one user in db.json with no state file yet — same intent, brand-new account. - * 4. Otherwise: throw with the list of options so the user can pick. - * - * The uid pattern `^[a-zA-Z0-9_-]+$` matches what api/server.js emits (base64url of 12 random - * bytes), and the sanitise on stateFile() above keeps a sneaky `..` in OPENGYM_UID harmless. - */ +// Pick the uid: OPENGYM_UID env, else the only state-* file, else the only user in db.json. +// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky +// '..' in OPENGYM_UID harmless. function resolveUid() { const envUid = (process.env.OPENGYM_UID || '').trim() if (envUid) { @@ -62,9 +47,9 @@ function resolveUid() { ) } -/** Set up the live state view: pick the uid, load db.json, attach the watcher, prime state. */ +// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state. export function init() { - if (_uid !== null) return // idempotent + if (_uid !== null) return if (!fs.existsSync(DATA_DIR)) throw new Error(`OPENGYM_DATA dir does not exist: ${DATA_DIR}`) _uid = resolveUid() reloadDb() @@ -75,11 +60,8 @@ export function init() { try { _loadedMtime = fs.statSync(file).mtimeMs } catch {} } if (_watcher) _watcher.close() - // fs.watch is best-effort: the watcher may briefly drop events under some filesystems, but - // its purpose is responsiveness (a tool call mid- ещё-one-sync), not durability — the api - // server's atomic write at PUT /api/data is the source of truth, and a stale read just gets - // corrected on the next change or the next tool call. We still re-read in getState() if the - // cached state is older than the file's mtime — covers the worst case of a missed event. + // fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of + // truth, and a stale read just gets corrected on the next change or the next tool call. try { _watcher = fs.watch(file, () => { // On change, simply clear the cache — the next getState() will re-read. Avoids reading @@ -90,17 +72,14 @@ export function init() { } catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ } } -/** Returns the state object (or null for a fresh account), re-reading on mtime change. */ +// Returns the state object, or null for a fresh account that never signed in on a device. export function getState() { init() const file = stateFile(_uid) - // fs.watch's reliability varies by filesystem — we still re-read whenever the file's mtime - // has changed since our last load. This covers watcher omissions, no-watcher platforms, and - // a call landed in the brief gap between the api server's atomic write and our event firing. + // Re-read if the file's mtime changed since our last load — covers watcher omissions and + // platforms with no fs.watch. let mtime try { mtime = fs.statSync(file).mtimeMs } catch { - // File no longer exists (account deleted since boot). Return what we have if anything; - // the caller handles null/undefined same as a fresh account. return _state === undefined ? null : _state } if (_state === undefined || mtime !== _loadedMtime) { @@ -117,21 +96,16 @@ export function getState() { return _state } -/** The user record (id + name) from db.json. Excludes passkeys/credentials and push subs. */ +// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs. export function getUser() { init() const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null } return { id: u.id, name: u.name, created: u.created || null } } -/** Path to the data dir (debug/test hook). */ export const dataDir = () => DATA_DIR -/** - * Test-only escape hatch: work against a passed-in state object instead of reading disk. - * The MCP server is read-only, so tests don't need to write files — pass any state object - * (typically from frontend/src/lib/demoSeed.js buildDemoState()) and the tools will use it. - */ +// Test-only: work against a passed-in state, not the disk. export function _seedStateForTests(state) { _uid = 'test-uid' _db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] } @@ -140,7 +114,6 @@ export function _seedStateForTests(state) { if (_watcher) { _watcher.close(); _watcher = null } } -/** The minimum shape the tools assume — fields default to empty/none if absent. */ function defaultsShape() { return { unit: 'kg', restSec: 90, sound: true, lang: 'en', diff --git a/mcp/src/tools.js b/mcp/src/tools.js index df794ad..517713a 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -1,13 +1,6 @@ -// The eight v1 tools — read-only views over a user's openGym state, computed by the same -// pure helpers the React UI uses (frontend/src/lib/*.js). Each handler returns JSON-shaped -// data the LLM can format as it likes; `labels.js` pre-substitutes any {0}/{1} template the -// lib returns so the LLM never re-implements the wording. -// -// Scope rules for these 8: -// • No passkey material, VAPID keys, session secrets — handlers never read or return them. -// • No raw db.json — only `getUser()` (id + name) plus the state file. -// • No in-progress ("active") workout data — the API never persists it; the file has none. -// • ISO dates validated (`YYYY-MM-DD`) so an LLM passing "yesterday" is rejected explicitly. +/* The eight read-only tools. Each handler returns JSON; labels.js pre-substitutes any + {0}/{1} template the lib returns so the LLM gets final text, not template strings. + ISO dates are validated on the way in; the handlers never see 'yesterday'. */ import { z } from 'zod' import { getState, getUser } from './state.js' import { @@ -31,8 +24,7 @@ function requireIso(v, name) { return s || null } -// Convert a workout entry into the JSON shape the tools expose. Everything the LLM needs to -// answer "what did I lift for X on day Y" lives here, including the mode tag and target. +// Drops ISO dates so an LLM passing 'yesterday' is rejected. function entryView(e, S) { const ex = exOr(e.id) const mode = modeOf(e.target || { id: e.id }) @@ -54,9 +46,7 @@ function entryView(e, S) { } } -// Best effort 1RM computation per exercise across a user's history. Mirrors newStats which -// powers the UI's PR table: take every eligible set across every workout and keep the biggest -// estimate per exercise, eligible = done + reps-mode + 1 <= reps <= REP_CAP (see onerm.js). +// Best estimate per exercise, mirroring the UI's PR table: every eligible set across history, biggest wins. function prTable(S, formula) { const byId = new Map() for (const w of (S.workouts || [])) { @@ -68,10 +58,8 @@ function prTable(S, formula) { const ex = exOr(e.id) const prev = byId.get(e.id) if (!prev || est > prev.est) { - // exId is included alongside exName because the consumer (the LLM, or our own - // estimate_1rm tool when called with one specific id) needs the id, not the name — - // exOr() falls back to treating any string as both id and name, so a caller passing - // exName where exId belongs would silently "work" against unknown exercises. + // exId as well as exName: the consumer needs an id, not a name — exOr() treats any + // string as both, so passing exName where exId belongs would silently "work" wrong. byId.set(e.id, { exId: e.id, exName: ex.n, bp: ex.bp || null, est, w: Number(s.w), r: Math.round(Number(s.r)), date: w.d }) } } @@ -82,7 +70,7 @@ function prTable(S, formula) { /* ---------- the 8 tools ---------- */ -/** 1. list_routines — names + counts of each routine in the user's plan. */ +/** list_routines — names + counts of each routine in the user's plan. */ export const listRoutines = { name: 'list_routines', description: 'List the workout routines saved in the user\'s openGym profile (the same list the Plan screen shows). Each routine is a named set of exercises with set/rep targets. Use this to discover the plan structure before diving into a specific routine or today\'s workout.', @@ -104,7 +92,7 @@ export const listRoutines = { } } -/** 2. get_routine — the full exercise list for one routine, including set/rep targets. */ +/** get_routine — the full exercise list for one routine, including set/rep targets. */ export const getRoutine = { name: 'get_routine', description: 'Get the full exercise list for a single routine (the same view the routine editor shows). Returns mode (reps/time/cardio), set/rep/weight targets, superset links, and any per-exercise custom increment you can override. Use routine_id from list_routines.', @@ -147,7 +135,7 @@ export const getRoutine = { } } -/** 3. get_week_plan — what's scheduled each weekday + today. */ +/** get_week_plan — what's scheduled each weekday + today. */ export const getWeekPlan = { name: 'get_week_plan', description: 'Show the user\'s weekly plan: which routine (if any) is assigned to each weekday, keyed by JS getDay() (Sunday=0, Monday=1, … Saturday=6 — the same convention the openGym state file uses). Also reports today\'s date and what routine applies today, accounting for one-off overrides the user may have set for a specific date (a "rest" override cancels the day).', @@ -181,7 +169,7 @@ export const getWeekPlan = { } } -/** 4. list_workouts — newest-first summary of recent sessions. */ +/** list_workouts — newest-first summary of recent sessions. */ export const listWorkouts = { name: 'list_workouts', description: 'List recent finished workouts, newest first. Each item summarises the date, exercise count, sets done / planned, total volume (in the user\'s unit), duration and whether PRs were set. Use this before drilling into a specific date with get_workout.', @@ -228,7 +216,7 @@ function plannedSets(w) { return n } -/** 5. get_workout — full entry/set breakdown for one date. */ +/** get_workout — full entry/set breakdown for one date. */ export const getWorkout = { name: 'get_workout', description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Use list_workouts first if you don\'t know the exact date.', @@ -254,7 +242,7 @@ export const getWorkout = { } } -/** 6. get_bodyweight — recent weigh-ins with the goal line. */ +/** get_bodyweight — recent weigh-ins with the goal line. */ export const getBodyweight = { name: 'get_bodyweight', description: 'Get the body-weight log: chronological weigh-ins with weights, current goal, deltas vs goal (signed positive = above goal), and a latest summary. Useful for "am I trending toward my weight goal?" questions.', @@ -286,7 +274,7 @@ export const getBodyweight = { } } -/** 7. estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */ +/** estimate_1rm — best-ever 1RM for one exercise or a PR table across all reps-mode exercises. */ export const estimate1rm = { name: 'estimate_1rm', description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`, @@ -302,8 +290,7 @@ export const estimate1rm = { const ex = exOr(exercise_id) const best = best1RM(S, exercise_id, f) const series = e1rmSeries(S, exercise_id, f) - // `w`/`r` (not `weight`/`reps`) match the field names used in pr_table and in - // get_workout's entry view — every set in the API surface uses the same couple. + // w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple. return { exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null }, formula: f, @@ -319,7 +306,7 @@ export const estimate1rm = { } } -/** 8. muscle_balance — training distribution per muscle over a period (week/month/all). */ +/** muscle_balance — training distribution per muscle over a period (week/month/all). */ export const muscleBalance = { name: 'muscle_balance', description: 'Show which muscles the user has trained in a period, ranked by "effective sets" (volume in kg is intentionally not used — 100 kg leg press vs 12 kg lateral raise say nothing about which muscle worked harder). Reports worked muscles with a 0-4 relative level (1 = some work, 4 = most worked) and the muscles trained zero times in that period — useful for "what am I neglecting?" questions.', diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 9d6210d..491aca0 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -1,28 +1,14 @@ -// Tool-layer tests against the demo seed fixture (frontend/src/lib/demoSeed.js) — the same -// data the public demo deployment at https://opengym.duarte-santos.ch runs on. -// -// What this file pins (and what it doesn't): -// • The JSON shape each tool returns (fields + types) for the happy path. -// • The actual computed VALUES for a few representative cases (1RM via Epley/Brzycki, -// workoutVolume, body-weight delta). The pure lib functions have their own 92 tests in -// frontend/src/lib/*.test.js — here we only sanity-check the wiring. -// • Edge cases that are easy to silently mishandle: rest-day override, ISO-date validation, -// no-workout history, no synced state, superset linking, time/cardio mode tags. -// -// "Today" is pinned to a fixed Monday (2026-07-27) so date-dependent tools (get_week_plan, -// muscle_balance) see consistent values regardless of when the suite runs. The demo -// state is built relative to that pinned time, so internal dates (e.g. dayPlan) align. -// -// We deliberately don't test the LLM-facing JSON-RPC transport here — that's the SDK's job, -// and the smoke test in scripts/ covers the wire-level handshake. Here we call the -// handler functions directly with already-validated args. +// Tool-layer tests for mcp/src/tools.js, seeded from frontend/src/lib/demoSeed.js — the same +// deterministic fixture the public demo runs on. The pure lib functions have their own 92 +// tests in frontend/src/lib/*.test.js; here we pin JSON shape + the user-facing edge cases +// (rest-day override, missing routine, zero-workout history, no synced state, superset links). import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest' import { buildDemoState } from '../../frontend/src/lib/demoSeed.js' import { _seedStateForTests } from '../src/state.js' import { TOOLS } from '../src/tools.js' -// Constants that originate from the lib (re-stated here so the assertions don't rely on a -//computer reading the lib to know what to expect — these are the values the demo state yields). +// Re-stated here so the assertions stand alone without reaching into lib internals to learn +// the demo state's exact values. const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled const GOAL_WEIGHT = 77 const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18500, bw: 78.6, sets_done: 20, sets_total: 20, duration_min: 51 } @@ -47,8 +33,7 @@ function freshState() { } // Pin "today" before building state so dayPlan/week alignment matches the assertions below. -// `toFake: ['Date']` only mocks the Date object — fs.watch / setTimeout in state.js keep -// working with the real event loop, so file watching and reaping stay untouched. +// `toFake: ['Date']` only — keeps fs.watch and the rest of the event loop real. beforeAll(() => { vi.useFakeTimers({ now: new Date(FAKE_TODAY_ISO + 'T12:00:00Z'), toFake: ['Date'] }) S = freshState() @@ -59,8 +44,7 @@ afterAll(() => { vi.useRealTimers() }) -// Each test sees a fresh clone of the seeded state — tests that mutate S.dayPlan (etc.) can -// never leak into a sibling test. ~1ms overhead per test, buys isolation. +// Fresh state per test — tests that mutate dayPlan can't leak into siblings. beforeEach(() => { S = freshState() _seedStateForTests(S) @@ -110,7 +94,7 @@ describe('get_routine', () => { }) }) - test('throws ENOENT on a bogus routine id (does not silently return empty)', () => { + test('throws ENOENT on a bogus routine id', () => { expect(() => call('get_routine', { routine_id: 'bogus' })).toThrow() }) diff --git a/mcp/vitest.config.js b/mcp/vitest.config.js index 19d1b06..f37fd1e 100644 --- a/mcp/vitest.config.js +++ b/mcp/vitest.config.js @@ -1,20 +1,11 @@ -// Vitest config for the MCP server tool tests. Mirrors the conventions of frontend/vite.config.js -// (no global config, no auto-watch, run once and exit) — kept in mcp/ rather than hoisted to the -// repo root so this package is self-contained and re-usable for any Node-side helper we add later. import { defineConfig } from 'vitest/config' export default defineConfig({ test: { include: ['test/**/*.test.js'], - // The tests import from ../src and ../../frontend/src/lib, both already ESM — no transform - // needed beyond what Vite does natively. Fake timers are used in tests that pin "today" - // (see tools.test.js header comment); they only mock Date, not setTimeout, so the file - // watcher in state.js (real setTimeout/setInterval via fs.watch) keeps working. globals: false, environment: 'node', pool: 'forks', - // Stryker spawns vitest per-mutant; isolating each test file in its own process keeps a - // crashing mutant from taking siblings down with it. Costs ~50ms/test, trade worth it. isolate: true, reporters: ['default'] } From 09949686c2907a5599ae1909283c261b069f72ee Mon Sep 17 00:00:00 2001 From: Pengboi Date: Sun, 2 Aug 2026 19:42:36 +0100 Subject: [PATCH 05/58] MCP: fixes from review (cardio mode, dead code, Stryker drop, docs) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit · entryView was passing `e.target || { id: e.id }` to modeOf, which doesn't put id on the target when target exists — so a cardio config saved as {sets, min, speed} (no mode, no id) fell through to 'reps' and the label came back as "0×0". Now uses the same pattern every app call site uses (Workout.jsx, Stats.jsx, progression.js): modeOf({ ...(e.target || {}), id: e.id }). Same fix applied to the setLabel call right below. Added a regression test using a real cardio exercise id with a target that has no mode key — would have caught the original bug. · requireIso/ISO/fmt/friendlyDate/MUSCLES were unused (zod regexes cover ISO validation at the SDK layer). Removed, along with the misplaced comment that described requireIso but sat above entryView. · estimate_1rm's exercise_id schema description referenced search_exercises (v1.5) which doesn't exist yet — an LLM reading the schema would try to call it. Dropped the reference; the Roadmap section in mcp/README.md drops the same mention. · resolveUid threw "set OPENGYM_UID to one of: " (empty list) when there were zero state files but multiple users in db.json — the files array was empty so files.join(', ') rendered nothing. Now falls back to the db.json user ids in that branch. · Dropped Stryker entirely. The MCP SDK's 93 transitive runtime packages are tolerable since mcp/ is opt-in and never enters Docker, but a second test toolchain for a 39% mutation score wasn't carrying its weight next to the plain vitest suite. Removed .stryker.conf.json, the two Stryker devDeps, the mutation:test script, the .gitignore entries, and the README section. mcp/ now has a single devDep (vitest); 0 vulnerabilities (was 2 moderate). · CONTRIBUTING.md layout block + a one-line cross-reference in README.md's Tech section pointing at mcp/README.md, so people can actually find it. 92 frontend + 33 MCP tests pass. --- .gitignore | 5 - CONTRIBUTING.md | 3 + README.md | 4 + mcp/.stryker.conf.json | 29 - mcp/README.md | 21 +- mcp/package-lock.json | 2089 +++------------------------------------- mcp/package.json | 5 +- mcp/src/state.js | 6 + mcp/src/tools.js | 22 +- mcp/test/tools.test.js | 18 + 10 files changed, 173 insertions(+), 2029 deletions(-) delete mode 100644 mcp/.stryker.conf.json diff --git a/.gitignore b/.gitignore index ff8dc43..12881fa 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,3 @@ frontend/dist/ node_modules/ *.log .DS_Store - -# Mutation-testing artifacts (mcp/) — reports/ is the HTML output, .stryker-tmp/ holds the -# backing copy used by `inPlace` mode during a run. Both regenerated on every `stryker run`. -mcp/reports/ -mcp/.stryker-tmp/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3e75f9c..93fe489 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,6 +12,9 @@ api/ backend — server.js (Node, no framework), one dependency (@simplewe web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api). media/ exercise img/gif (gitignored, fetched at runtime). docs/ self-hosting guide. +mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps + (Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in + the Docker build; only runs when an LLM client spawns it. See mcp/README.md. ``` ## Running for development diff --git a/README.md b/README.md index aa9eb4e..011c277 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,10 @@ lives in pure functions under `frontend/src/lib/` with tests next to them: `npm `frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond React, the router and Zustand. +The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like +Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not +in the Docker build. + ## Contributing Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: more starter diff --git a/mcp/.stryker.conf.json b/mcp/.stryker.conf.json deleted file mode 100644 index a564d45..0000000 --- a/mcp/.stryker.conf.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "./node_modules/@stryker-mutator/core/schema/stryker-schema.json", - "packageManager": "npm", - "testRunner": "vitest", - "vitest": { - "configFile": "vitest.config.js", - "related": false - }, - "coverageAnalysis": "perTest", - "mutate": [ - "src/state.js", - "src/labels.js", - "src/tools.js" - ], - "testFiles": [ - "test/**/*.test.js" - ], - "inPlace": true, - "ignorePatterns": [], - "thresholds": { - "high": 80, - "low": 60, - "break": 0 - }, - "reporters": ["html", "progress", "clear-text"], - "concurrency": 2, - "disableTypeChecks": true, - "cleanTempDir": true -} diff --git a/mcp/README.md b/mcp/README.md index 9007e0e..77b2641 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -119,28 +119,11 @@ missing routine, zero-workout history, no synced state, superset links, three 1R tools see consistent values regardless of when the suite runs. The pure lib functions have their own 92 tests in `frontend/src/lib/*.test.js`. -## Mutation testing - -```bash -cd mcp && npm run mutation:test -``` - -[Stryker](https://stryker-mutator.io) 9.6.1 against the three MCP-only modules in `src/` -(`frontend/src/lib/` is excluded — it has its own 92-test suite). Config at -`.stryker.conf.json`. Run uses `inPlace: true` so the test file's relative imports -`../../frontend/src/lib/*.js` keep resolving; Stryker keeps a backup in `.stryker-tmp/` -during the run and restores on exit. - -Baseline: 39% mutation score (333 killed / 330 survived / 184 no-coverage). Most of the -survivors are zod schema string literals; the bulk of the no-coverage debt lives in -`state.js` (file watching, multi-user resolution, mtime fallback). HTML report at -`mcp/reports/mutation/mutation.html` (gitignored, regenerated per run). - ## Roadmap - **Done (Phase 1):** read-only stdio, 8 tools, direct `./data` access. -- **Phase 1.5:** `progression_next` (what does the policy prescribe next?) + `search_exercises` - (search the catalog). No new deps; small surface area. +- **Phase 1.5:** a `progression_next` tool (what does the policy prescribe next?). No new + deps; small surface area. - **Phase 2:** read+write over stdio. Requires a long-lived token auth path minted from the admin dashboard (new `./data/tokens.json`) and a write-lock against the web UI's read-modify- write of `state-.json`. Tools: `log_workout`, `add_bodyweight`, `edit_routine`, diff --git a/mcp/package-lock.json b/mcp/package-lock.json index da4fbad..f29cb60 100644 --- a/mcp/package-lock.json +++ b/mcp/package-lock.json @@ -16,558 +16,25 @@ "opengym-mcp": "src/index.js" }, "devDependencies": { - "@stryker-mutator/core": "^9.6.1", - "@stryker-mutator/vitest-runner": "^9.6.1", "vitest": "^4.1.10" } }, - "node_modules/@babel/code-frame": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", - "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.29.7", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", - "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", - "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-compilation-targets": "^7.29.7", - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helpers": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", - "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-annotate-as-pure": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz", - "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", - "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.29.7", - "@babel/helper-validator-option": "^7.29.7", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz", - "integrity": "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/helper-replace-supers": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/traverse": "^7.29.7", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", - "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz", - "integrity": "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", - "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", - "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-optimise-call-expression": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz", - "integrity": "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", - "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-replace-supers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz", - "integrity": "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-member-expression-to-functions": "^7.29.7", - "@babel/helper-optimise-call-expression": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz", - "integrity": "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", - "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", - "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", - "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", - "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", - "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.7" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-proposal-decorators": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-decorators/-/plugin-proposal-decorators-7.29.7.tgz", - "integrity": "sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/plugin-syntax-decorators": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-decorators": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-decorators/-/plugin-syntax-decorators-7.29.7.tgz", - "integrity": "sha512-9MTTLbF39X6sqM92JPEsoI7++26hjZvzkxKZy64aMhWLH2mPkJ/Q3AV4QLmls3R14FpSpkOwQQfUh962JGQxxg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", - "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", - "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-destructuring": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.7.tgz", - "integrity": "sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/traverse": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-explicit-resource-management": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-explicit-resource-management/-/plugin-transform-explicit-resource-management-7.29.7.tgz", - "integrity": "sha512-Rstj7coNz8sE+7Ju7ihpHLI564lsK5pUpNNlvptCIC/16E/S5hbl6n3kESPKdNRmqEWlpn5xpS5Q2dvXBsySLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/plugin-transform-destructuring": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz", - "integrity": "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-transforms": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.7.tgz", - "integrity": "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.29.7", - "@babel/helper-create-class-features-plugin": "^7.29.7", - "@babel/helper-plugin-utils": "^7.29.7", - "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", - "@babel/plugin-syntax-typescript": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/preset-typescript": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/preset-typescript/-/preset-typescript-7.28.5.tgz", - "integrity": "sha512-+bQy5WOI2V6LJZpPVxY+yp66XdZ2yifu0Mc1aP5CQKgjn4QM5IN2i5fAZ4xKop47pr8rpVhiAeu+nDQa12C8+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1", - "@babel/helper-validator-option": "^7.27.1", - "@babel/plugin-syntax-jsx": "^7.27.1", - "@babel/plugin-transform-modules-commonjs": "^7.27.1", - "@babel/plugin-transform-typescript": "^7.28.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", - "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/types": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", - "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.7", - "@babel/generator": "^7.29.7", - "@babel/helper-globals": "^7.29.7", - "@babel/parser": "^7.29.7", - "@babel/template": "^7.29.7", - "@babel/types": "^7.29.7", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", - "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.29.7", - "@babel/helper-validator-identifier": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@emnapi/core": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz", - "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==", + "version": "2.0.0-alpha.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-alpha.3.tgz", + "integrity": "sha512-AZypUeJ/yByuxyS7BlSNRDOMLMlROYtjYdIAuBmJssVz1UJDSeYxLrdizhXCFYhedC5bqd/ASy8EuNXbVVXp9g==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.2", + "@emnapi/wasi-threads": "2.0.1", "tslib": "^2.4.0" } }, "node_modules/@emnapi/runtime": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz", - "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==", + "version": "2.0.0-alpha.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-alpha.3.tgz", + "integrity": "sha512-hFPAhMUjJD9BSyCANEISPOogeXC9Zo9ZQl7L6vKnaVsMkCtzznaW/naYypeyl0Gv5rYfWYsZbpixTMpjDJzQeA==", "dev": true, "license": "MIT", "optional": true, @@ -576,9 +43,9 @@ } }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", - "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.0.1.tgz", + "integrity": "sha512-9DsSk+o5NBX0CCJT8s0EROGSGxjR/tKu6aBTaVyq+SjAEQH4XcdcRxPBRzsBLizTTJ49MJjF+jgu3qnO9GLQcQ==", "dev": true, "license": "MIT", "optional": true, @@ -587,393 +54,17 @@ } }, "node_modules/@hono/node-server": { - "version": "1.19.15", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.15.tgz", - "integrity": "sha512-Za2ai6TLdKjUvnur+eenO6nuYYipVAEhyCAdaV8IRvmU9kK8crOZUSYvIXn72E4f8fJqyAbpcJuTsYYmZp9Deg==", + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.0.12.tgz", + "integrity": "sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==", "license": "MIT", "engines": { - "node": ">=18.14.1" + "node": ">=20" }, "peerDependencies": { "hono": "^4" } }, - "node_modules/@inquirer/ansi": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.7.tgz", - "integrity": "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - } - }, - "node_modules/@inquirer/checkbox": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.1.tgz", - "integrity": "sha512-b6xmA/VlTe0ZgDQHDui+Nav470u7u49nRd8/iuhOcQPO9Ch7lGuogydhi2VOmNlZ+zXcM8IcPuNSwQcdJaF/kw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.7", - "@inquirer/core": "^11.2.1", - "@inquirer/figures": "^2.0.7", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/confirm": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.1.1.tgz", - "integrity": "sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/core": { - "version": "11.2.1", - "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-11.2.1.tgz", - "integrity": "sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.7", - "@inquirer/figures": "^2.0.7", - "@inquirer/type": "^4.0.7", - "cli-width": "^4.1.0", - "fast-wrap-ansi": "^0.2.0", - "mute-stream": "^3.0.0", - "signal-exit": "^4.1.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/editor": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.2.2.tgz", - "integrity": "sha512-ZRVd/oD+sYsUd5zVm0NflqEzlqfYCyHNsqkHl2oWXEUHs12tCbcSFi+wVFEvD8+LGRaMUsVrE7qeo6lSG/S1Vg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/external-editor": "^3.0.3", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/expand": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.1.tgz", - "integrity": "sha512-YmQpenjbFSHAK3sOd44puHh3V1KXXr+JiNpUztoSQ4drLh2rTVzTap/YtlAVu/5xavifIlBfNEzJ/neZJ1a/1g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/external-editor": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.3.tgz", - "integrity": "sha512-6thf5I8q7lZwzGLAxPaaGEREEkZ3nyePPDQ1oyobblxmEE8mqTLguScP7pDjUTAibiyb4hfXl+qjUEJ+di/aNA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chardet": "^2.1.1", - "iconv-lite": "^0.7.2" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/figures": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.7.tgz", - "integrity": "sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - } - }, - "node_modules/@inquirer/input": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.2.tgz", - "integrity": "sha512-9K/DDBSQpOyZSkt6sOVP9Vo0TR7atX2kuILsUu0x3wVcVbe97lJwIJKMLdMw25tDYuXl/qp6erT0Xs1rfmcfZg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/number": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.1.1.tgz", - "integrity": "sha512-XF4IXAbPnGPgw0wsbC/i2tPcyfdZgDpUlhsqU0SfT4IRIGWha6Xm9VRgN5yYxJq+jnyXlfXI/nQ3ulfk0iEICA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/password": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.1.1.tgz", - "integrity": "sha512-3XBfF7DAsp5qeDsvN5Rd1HmbNokVvEQoUM0QLrRcybC9nX96w3Pbmu7qUsb3IT3J3jBvs2+mTXaKHOUsgHMLzg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.7", - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/prompts": { - "version": "8.5.2", - "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.5.2.tgz", - "integrity": "sha512-IYR/3C/paEVVQYQvdDlFZVjRCJVYHHON0XXMH91KO9GSxs0TdKYWlUdvfQl2EfAHDxUaN3IBffkE/BDTh5nJ6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/checkbox": "^5.2.1", - "@inquirer/confirm": "^6.1.1", - "@inquirer/editor": "^5.2.2", - "@inquirer/expand": "^5.1.1", - "@inquirer/input": "^5.1.2", - "@inquirer/number": "^4.1.1", - "@inquirer/password": "^5.1.1", - "@inquirer/rawlist": "^5.3.1", - "@inquirer/search": "^4.2.1", - "@inquirer/select": "^5.2.1" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/rawlist": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.1.tgz", - "integrity": "sha512-QqdTqQddL3qPX/PPrjobpsO25NZ4dWXgTLenrR445L2ptLEYE6Z+PD5c5CNDJNx4ugRgELAIpSIJxZaO2jJ2Og==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/search": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.2.1.tgz", - "integrity": "sha512-xJj8QWKRSrfKoBIITLZK61dD3zwo0Rz11fgDImku30/Oe81zMdIdGgrLY2h6RkJ+KZ/GhNYIRMKnH/62qBTA5g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.2.1", - "@inquirer/figures": "^2.0.7", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/select": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.1.tgz", - "integrity": "sha512-FlDndEUww8m7BfukO2nJa25vhD+H5jxxCv4oGioKqzyWz3nPHhhw4LKdYRSlXuAx7DsdWia7iyaBPKKS95Evfw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.7", - "@inquirer/core": "^11.2.1", - "@inquirer/figures": "^2.0.7", - "@inquirer/type": "^4.0.7" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/type": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.0.7.tgz", - "integrity": "sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^20.17.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", @@ -981,24 +72,13 @@ "dev": true, "license": "MIT" }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, "node_modules/@modelcontextprotocol/sdk": { - "version": "1.29.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", - "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", + "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", "license": "MIT", "dependencies": { - "@hono/node-server": "^1.19.9", + "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", @@ -1033,28 +113,31 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz", - "integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.2.tgz", + "integrity": "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw==", "dev": true, "license": "MIT", "optional": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, "funding": { "type": "github", "url": "https://github.com/sponsors/Brooooooklyn" }, "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" } }, "node_modules/@oxc-project/types": { - "version": "0.139.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.139.0.tgz", - "integrity": "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==", + "version": "0.142.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.142.0.tgz", + "integrity": "sha512-7W+2q5AKQVU36fkaryontrHn3YDt1RyUYXatw9i5H8ocYe2sPKSFB6eS8WNPeRKiN1qAWWZUPm7gwFzJGrccqQ==", "dev": true, "license": "MIT", "funding": { @@ -1062,9 +145,9 @@ } }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz", - "integrity": "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.1.tgz", + "integrity": "sha512-02hOeOSryYxVrOIphmLAsqnCJWxwlzFk+pEt/N/i6OgT3lShHO7xGCU5cpgchRDHboAEbSjzgGh+O/u1GswQmA==", "cpu": [ "arm64" ], @@ -1079,9 +162,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.5.tgz", - "integrity": "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.1.tgz", + "integrity": "sha512-fMsTOnN0OjFm3CyppWPitKnc8UlliVARUULW6cfU6AIqjdtgmSFWSk9vecHzZduv/yMWIHDlRhM1e8Iff9uAfA==", "cpu": [ "arm64" ], @@ -1096,9 +179,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.5.tgz", - "integrity": "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.1.tgz", + "integrity": "sha512-1wjKdz/XLGKHaTNHjQveQ/B23TKx4ItAqm1JbyVuvNPc4Ze0Fb48s49TAd/2zcplPl8okE/UbTgmlVfwT7eFeQ==", "cpu": [ "x64" ], @@ -1113,9 +196,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.5.tgz", - "integrity": "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.1.tgz", + "integrity": "sha512-Fa0jHR07E7YBN4vOEsbVf2briYNsuOowfLJaXULZM0ldMlaCaj2LJgLMbMe4iacRyZmvR8efFhgR9wKuGclQUg==", "cpu": [ "x64" ], @@ -1130,9 +213,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.5.tgz", - "integrity": "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.1.tgz", + "integrity": "sha512-pzkgu1SSHGgRRyRZ4fbmSgmajbVt+epaLP99NDjFft69v/ypfTi6swBMiVdh2EkQ0OSnHE1lZDM7DRGkyAzUpA==", "cpu": [ "arm" ], @@ -1147,9 +230,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.5.tgz", - "integrity": "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.1.tgz", + "integrity": "sha512-QI5SEDY8cbiYWHx0VO4vIc3UlS6a32vXHjU8Qy/17adEmZIPuByJg13UEvo9c/UCiUkdcVWY83C+b+JrwnNyUg==", "cpu": [ "arm64" ], @@ -1167,9 +250,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.5.tgz", - "integrity": "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.1.tgz", + "integrity": "sha512-Sm41FyCeXqmYcERoYOCbGIL5hNfd8w9LQ7Y61Bev48HkcjaJqV/iiVOaiDxjVTRMS+QKrZmD8cfPt4uMVnvM+A==", "cpu": [ "arm64" ], @@ -1187,9 +270,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.5.tgz", - "integrity": "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.1.tgz", + "integrity": "sha512-2x+WhXTGl9yJYPbltW/BSEPTVz9OIWQyER4N+gJEDWkkn904eRcBzELqh/Hf7K0w/ubGbKNMv0ZC+94QK/IFEg==", "cpu": [ "ppc64" ], @@ -1207,9 +290,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.5.tgz", - "integrity": "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.1.tgz", + "integrity": "sha512-eEjmQpuRQayHPWWnywaWHkFT3ToPbP3RYy42VVd/B9aBGDA+Ol25EIWHxKQST3IiWJjikCWUF7KtbfqwZrzVwQ==", "cpu": [ "s390x" ], @@ -1227,9 +310,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.5.tgz", - "integrity": "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.1.tgz", + "integrity": "sha512-/Orga1fZYkLc/56jBICcHrKchl8Z2UKdDSr3LG9ToWO1lQ6a4Livk9Xz+9WN91zsz5QR3XQz2NNoSDEvP6qadw==", "cpu": [ "x64" ], @@ -1247,9 +330,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.5.tgz", - "integrity": "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.1.tgz", + "integrity": "sha512-xxBJRL+0q0Kce7orznGWLuylHDY65vuARXZRpX+hPdv+DqK2c3NlCsVA98tlWzWNEE7yPqA/1NQ5nnCrj49Y5A==", "cpu": [ "x64" ], @@ -1267,9 +350,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.5.tgz", - "integrity": "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.1.tgz", + "integrity": "sha512-M6AdXIXw3s+/8XpKMzdGDEXGS1S7kwUsy+rcTIUIOx5Ge4nXKCtAFHFV9YKkXvGcC5WMoTjAteLzlsQROVI0Yw==", "cpu": [ "arm64" ], @@ -1284,28 +367,25 @@ } }, "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.5.tgz", - "integrity": "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA==", - "cpu": [ - "wasm32" - ], + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.1.tgz", + "integrity": "sha512-/TX0SoRGojHzSAHpfVBbavRVSazg5U3h3Y3VXfcc0cdugq6kxdqw8LPGFiPr+/7gE/60zRcsOY2Vi9b9eT0jww==", "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "1.11.1", - "@emnapi/runtime": "1.11.1", - "@napi-rs/wasm-runtime": "^1.1.6" + "@emnapi/core": "2.0.0-alpha.3", + "@emnapi/runtime": "2.0.0-alpha.3", + "@napi-rs/wasm-runtime": "^1.2.0" }, "engines": { - "node": "^20.19.0 || >=22.12.0" + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" } }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.5.tgz", - "integrity": "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.1.tgz", + "integrity": "sha512-EvRrivJieyHG+AO9lleZWgq+g0+S7oV2C51yuqlcyU/R9net+sI4Pj0F+lUoP2bEr6TWX3SqFaaS0SzfLxSzkw==", "cpu": [ "arm64" ], @@ -1320,9 +400,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.5.tgz", - "integrity": "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.1.tgz", + "integrity": "sha512-Z4eCmn5QJ/5+azF9knpLWKfVd9aidn0mAe9TpJgvBLId9Ax3t0+JVxBmT25Bv7NBbVW1TZyKjQjQReouMeH5UQ==", "cpu": [ "x64" ], @@ -1343,26 +423,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@sec-ant/readable-stream": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", - "integrity": "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sindresorhus/merge-streams": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz", - "integrity": "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -1370,144 +430,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@stryker-mutator/api": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@stryker-mutator/api/-/api-9.6.1.tgz", - "integrity": "sha512-g8VNoFWQWbx0pdal3Vt8jVCZW+v3sc3gi94iI0GVtVgUGTqphAjJF6EAruPTx0lqvtonsaAxn5TD36hcG1d6Wg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "mutation-testing-metrics": "3.7.3", - "mutation-testing-report-schema": "3.7.3", - "tslib": "~2.8.0", - "typed-inject": "~5.0.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@stryker-mutator/core": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@stryker-mutator/core/-/core-9.6.1.tgz", - "integrity": "sha512-WMgnvf+Wyh/yiruhNZwc8w8DlzmmjXhPjSn5MR8RhAXzlnWji8TQrUYgBUkHk9bEgSaIlB3KZHm37iiU5Q2cLQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@inquirer/prompts": "^8.0.0", - "@stryker-mutator/api": "9.6.1", - "@stryker-mutator/instrumenter": "9.6.1", - "@stryker-mutator/util": "9.6.1", - "ajv": "~8.18.0", - "chalk": "~5.6.0", - "commander": "~14.0.0", - "diff-match-patch": "1.0.5", - "emoji-regex": "~10.6.0", - "execa": "~9.6.0", - "json-rpc-2.0": "^1.7.0", - "lodash.groupby": "~4.6.0", - "minimatch": "~10.2.4", - "mutation-server-protocol": "~0.4.0", - "mutation-testing-elements": "3.7.3", - "mutation-testing-metrics": "3.7.3", - "mutation-testing-report-schema": "3.7.3", - "npm-run-path": "~6.0.0", - "progress": "~2.0.3", - "rxjs": "~7.8.1", - "semver": "^7.6.3", - "source-map": "~0.7.4", - "tree-kill": "~1.2.2", - "tslib": "2.8.1", - "typed-inject": "~5.0.0", - "typed-rest-client": "~2.3.0" - }, - "bin": { - "stryker": "bin/stryker.js" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@stryker-mutator/core/node_modules/ajv": { - "version": "8.18.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", - "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/@stryker-mutator/instrumenter": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@stryker-mutator/instrumenter/-/instrumenter-9.6.1.tgz", - "integrity": "sha512-5K8wH4Pthly25c2uKKik4Dfcoeou7sbJdFS6u3QIYHlulgFVDJwtEMWTZGkZfs7IiUEXIDNa0keRACq5jn5AvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@babel/core": "~7.29.0", - "@babel/generator": "~7.29.0", - "@babel/parser": "~7.29.0", - "@babel/plugin-proposal-decorators": "~7.29.0", - "@babel/plugin-transform-explicit-resource-management": "^7.28.0", - "@babel/preset-typescript": "~7.28.0", - "@stryker-mutator/api": "9.6.1", - "@stryker-mutator/util": "9.6.1", - "angular-html-parser": "~10.4.0", - "semver": "~7.7.0", - "tslib": "2.8.1", - "weapon-regex": "~1.3.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@stryker-mutator/instrumenter/node_modules/semver": { - "version": "7.7.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", - "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@stryker-mutator/util": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@stryker-mutator/util/-/util-9.6.1.tgz", - "integrity": "sha512-Lk/ALVctJjFv1vvwR+CFoKzDCWvsBlq7flDUnmnpuwTrGbm156EdZD1Jjq4o8KdOap0ezUZqQNE9OAI1m2+pUQ==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/@stryker-mutator/vitest-runner": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@stryker-mutator/vitest-runner/-/vitest-runner-9.6.1.tgz", - "integrity": "sha512-eyUHTCf3Ui+SUn/tpFJwzw6MV391kyBLZk/cDHFUfKFELqKMLbvd7e81axArlApKqO6cOnLfrxlwED+2SRN0ow==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@stryker-mutator/api": "9.6.1", - "@stryker-mutator/util": "9.6.1", - "semver": "^7.7.4", - "tslib": "~2.8.0" - }, - "engines": { - "node": ">=14.18.0" - }, - "peerDependencies": { - "@stryker-mutator/core": "9.6.1", - "vitest": ">=2.0.0" - } - }, "node_modules/@tybys/wasm-util": { "version": "0.10.3", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", @@ -1703,16 +625,6 @@ } } }, - "node_modules/angular-html-parser": { - "version": "10.4.0", - "resolved": "https://registry.npmjs.org/angular-html-parser/-/angular-html-parser-10.4.0.tgz", - "integrity": "sha512-++nLNyZwRfHqFh7akH5Gw/JYizoFlMRz0KRigfwfsLqV8ZqlcVRb1LkPEWdYvEKDnbktknM2J4BXaYUGrQZPww==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1723,29 +635,6 @@ "node": ">=12" } }, - "node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/baseline-browser-mapping": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.4.tgz", - "integrity": "sha512-s4+sLr9mZ/CyqeRritFeYV/Zx73OAtmaHn6kkBS1XRoJn1hrg3xIDUcpicAEX68tkcIN0iBCgti31C8zxtkhsQ==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/body-parser": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", @@ -1783,53 +672,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/brace-expansion": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.8.tgz", - "integrity": "sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/browserslist": { - "version": "4.28.7", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.7.tgz", - "integrity": "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.10.44", - "caniuse-lite": "^1.0.30001806", - "electron-to-chromium": "^1.5.393", - "node-releases": "^2.0.51", - "update-browserslist-db": "^1.2.3" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1868,27 +710,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/caniuse-lite": { - "version": "1.0.30001806", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001806.tgz", - "integrity": "sha512-72Cuvd95zbSYPKq6Fhg8eDJRlzgWDf7/mtoZv6Qe/DYNCEBdNxoA3+rZAU2ZhGCpZlns3EssFavaZomckT5Uuw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, "node_modules/chai": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", @@ -1899,46 +720,6 @@ "node": ">=18" } }, - "node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chardet": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz", - "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==", - "dev": true, - "license": "MIT" - }, - "node_modules/cli-width": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", - "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 12" - } - }, - "node_modules/commander": { - "version": "14.0.3", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", - "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20" - } - }, "node_modules/content-disposition": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", @@ -2043,17 +824,6 @@ "node": ">= 0.8" } }, - "node_modules/des.js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.1.0.tgz", - "integrity": "sha512-r17GxjhUCjSRy8aiJpr8/UadFIzMzJGexI3Nmz4ADi9LYSFx4gTBp80+NaX/YsXWWLhpZ7v/v/ubEc/bCNfKwg==", - "dev": true, - "license": "MIT", - "dependencies": { - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0" - } - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2064,13 +834,6 @@ "node": ">=8" } }, - "node_modules/diff-match-patch": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz", - "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -2091,20 +854,6 @@ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", "license": "MIT" }, - "node_modules/electron-to-chromium": { - "version": "1.5.396", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.396.tgz", - "integrity": "sha512-yHiw2Y3C3H9U6TMbOfoWK/BPreiOPXRfTWPBwQBoZG6/8TB6eOPnsy5oaRYuatR7Fw2SJ4kKforgufeo7fq0EQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/emoji-regex": { - "version": "10.6.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", - "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", - "dev": true, - "license": "MIT" - }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -2151,16 +900,6 @@ "node": ">= 0.4" } }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -2207,33 +946,6 @@ "node": ">=18.0.0" } }, - "node_modules/execa": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-9.6.1.tgz", - "integrity": "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sindresorhus/merge-streams": "^4.0.0", - "cross-spawn": "^7.0.6", - "figures": "^6.1.0", - "get-stream": "^9.0.0", - "human-signals": "^8.0.1", - "is-plain-obj": "^4.1.0", - "is-stream": "^4.0.1", - "npm-run-path": "^6.0.0", - "pretty-ms": "^9.2.0", - "signal-exit": "^4.1.0", - "strip-final-newline": "^4.0.0", - "yoctocolors": "^2.1.1" - }, - "engines": { - "node": "^18.19.0 || >=20.5.0" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, "node_modules/expect-type": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", @@ -2288,9 +1000,9 @@ } }, "node_modules/express-rate-limit": { - "version": "8.6.0", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.0.tgz", - "integrity": "sha512-XKJXDsASUOo0LLtFwW5hCcQGH0N4WQc/Rn8/Pvoia+TJFOkkFPvrtW9lZOeeNcxQJspvOIERMwiRLsVFlhHEkA==", + "version": "8.6.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.1.tgz", + "integrity": "sha512-0D493aP61w0TJ2A0wy27riRsO7FMQ7FK+KUHOKCSfPvYo0R55aiC6emCVgFUeShH0fq0ICPVzNcgoS+BsbXQCA==", "license": "MIT", "dependencies": { "debug": "^4.4.3", @@ -2312,27 +1024,10 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", "license": "MIT" }, - "node_modules/fast-string-truncated-width": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", - "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-string-width": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", - "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-truncated-width": "^3.0.2" - } - }, "node_modules/fast-uri": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", - "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", + "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", "funding": [ { "type": "github", @@ -2345,16 +1040,6 @@ ], "license": "BSD-3-Clause" }, - "node_modules/fast-wrap-ansi": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz", - "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-width": "^3.0.2" - } - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2373,22 +1058,6 @@ } } }, - "node_modules/figures": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", - "integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-unicode-supported": "^2.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/finalhandler": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", @@ -2452,16 +1121,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -2499,23 +1158,6 @@ "node": ">= 0.4" } }, - "node_modules/get-stream": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz", - "integrity": "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sec-ant/readable-stream": "^0.4.1", - "is-stream": "^4.0.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2553,9 +1195,9 @@ } }, "node_modules/hono": { - "version": "4.12.32", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.32.tgz", - "integrity": "sha512-XcuyW9qE2kJn07PkecMOBd5Vq/hMy7mmGw+idz1yblbg9N17ijJODrvPkn7/dwL3Kulj8LcRJ69DLOWf91dRUg==", + "version": "4.12.33", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.33.tgz", + "integrity": "sha512-+SwvkaiJtxsiPjhy9LivY/1m7UsNqCJetM1BrZl9A5DkQhlbHQDU730mMiDPWjnoCYOM8Chf3WrCJw27kNTPFQ==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -2581,16 +1223,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/human-signals": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz", - "integrity": "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18.0" - } - }, "node_modules/iconv-lite": { "version": "0.7.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", @@ -2614,9 +1246,9 @@ "license": "ISC" }, "node_modules/ip-address": { - "version": "10.3.1", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.3.1.tgz", - "integrity": "sha512-1e9d3kb97NHJTIJDZW9rKqW2h6+dFa50Dy0fpPSMQp2ADje5gvKsXmdiK6dwY5t76TaTt5+P5N1Y/LoToIxP6g==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz", + "integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==", "license": "MIT", "engines": { "node": ">= 12" @@ -2631,51 +1263,12 @@ "node": ">= 0.10" } }, - "node_modules/is-plain-obj": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", - "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "license": "MIT" }, - "node_modules/is-stream": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz", - "integrity": "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-unicode-supported": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", - "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -2683,48 +1276,14 @@ "license": "ISC" }, "node_modules/jose": { - "version": "6.2.4", - "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.4.tgz", - "integrity": "sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==", + "version": "6.2.7", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.7.tgz", + "integrity": "sha512-hq1OB1bALKfydZNoViyg6hPVGV4i93ny9Op+n4zP5RSf7SCZEXa/TsG2O3IEr7+WlHRTPnpqDmHfMH6qXAD60w==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/panva" } }, - "node_modules/js-md4": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/js-md4/-/js-md4-0.3.2.tgz", - "integrity": "sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA==", - "dev": true, - "license": "MIT" - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-rpc-2.0": { - "version": "1.7.1", - "resolved": "https://registry.npmjs.org/json-rpc-2.0/-/json-rpc-2.0-1.7.1.tgz", - "integrity": "sha512-JqZjhjAanbpkXIzFE7u8mE/iFblawwlXtONaCvRqI+pyABVz7B4M1EUNpyVW+dZjqgQ2L5HFmZCmOCgUKm00hg==", - "dev": true, - "license": "MIT" - }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -2737,19 +1296,6 @@ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", "license": "BSD-2-Clause" }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", @@ -3023,23 +1569,6 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/lodash.groupby": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", - "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", - "dev": true, - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -3109,92 +1638,12 @@ "url": "https://opencollective.com/express" } }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "dev": true, - "license": "ISC" - }, - "node_modules/minimatch": { - "version": "10.2.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", - "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.5" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, - "node_modules/mutation-server-protocol": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/mutation-server-protocol/-/mutation-server-protocol-0.4.1.tgz", - "integrity": "sha512-SBGK0j8hLDne7bktgThKI8kGvGTx3rY3LAeQTmOKZ5bVnL/7TorLMvcVF7dIPJCu5RNUWhkkuF53kurygYVt3g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "zod": "^4.1.12" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/mutation-server-protocol/node_modules/zod": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", - "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, - "node_modules/mutation-testing-elements": { - "version": "3.7.3", - "resolved": "https://registry.npmjs.org/mutation-testing-elements/-/mutation-testing-elements-3.7.3.tgz", - "integrity": "sha512-SMeIPxngJpfjfNYctFpYQQtlBlZaVO0aoB3FKdwrI8Ee/2bkyUuCZzAOCLv1U9fnmfA37dPFq0Owduoxs2XgGQ==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/mutation-testing-metrics": { - "version": "3.7.3", - "resolved": "https://registry.npmjs.org/mutation-testing-metrics/-/mutation-testing-metrics-3.7.3.tgz", - "integrity": "sha512-B8QrP0ZomErzTPNlhrzKWPNBln+3afwBZPHv0Q7N8wZZTYxMptzb/Gdm3ExXVmioVYrtZAtsDs7W/T/b2AixOQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "mutation-testing-report-schema": "3.7.3" - } - }, - "node_modules/mutation-testing-report-schema": { - "version": "3.7.3", - "resolved": "https://registry.npmjs.org/mutation-testing-report-schema/-/mutation-testing-report-schema-3.7.3.tgz", - "integrity": "sha512-BHm3MYq+ckO+t5CtlG8zpqxc75rdJCkxVlE+fGuGJM3F7tNCQ/OW2N+TQVHN3BHsYa84+BFc6g3AwDYkUsw2MA==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/mute-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", - "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, "node_modules/nanoid": { "version": "3.3.16", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", @@ -3223,46 +1672,6 @@ "node": ">= 0.6" } }, - "node_modules/node-releases": { - "version": "2.0.51", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.51.tgz", - "integrity": "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/npm-run-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz", - "integrity": "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^4.0.0", - "unicorn-magic": "^0.3.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npm-run-path/node_modules/path-key": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", - "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -3319,19 +1728,6 @@ "wrappy": "1" } }, - "node_modules/parse-ms": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", - "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -3397,9 +1793,9 @@ } }, "node_modules/postcss": { - "version": "8.5.23", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.23.tgz", - "integrity": "sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==", + "version": "8.5.25", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz", + "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==", "dev": true, "funding": [ { @@ -3425,32 +1821,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/pretty-ms": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.0.tgz", - "integrity": "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parse-ms": "^4.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/progress": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", - "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -3518,13 +1888,13 @@ } }, "node_modules/rolldown": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz", - "integrity": "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.1.tgz", + "integrity": "sha512-4FKJhg8d3OiyQOA6Q1Q0hoFFpW9/OoX+VsHzpECsdsIZoOArrAK90gl59YK/Z+gnDel45bgJZK03ozH/9bCqEw==", "dev": true, "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.139.0", + "@oxc-project/types": "=0.142.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -3534,21 +1904,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.1.5", - "@rolldown/binding-darwin-arm64": "1.1.5", - "@rolldown/binding-darwin-x64": "1.1.5", - "@rolldown/binding-freebsd-x64": "1.1.5", - "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", - "@rolldown/binding-linux-arm64-gnu": "1.1.5", - "@rolldown/binding-linux-arm64-musl": "1.1.5", - "@rolldown/binding-linux-ppc64-gnu": "1.1.5", - "@rolldown/binding-linux-s390x-gnu": "1.1.5", - "@rolldown/binding-linux-x64-gnu": "1.1.5", - "@rolldown/binding-linux-x64-musl": "1.1.5", - "@rolldown/binding-openharmony-arm64": "1.1.5", - "@rolldown/binding-wasm32-wasi": "1.1.5", - "@rolldown/binding-win32-arm64-msvc": "1.1.5", - "@rolldown/binding-win32-x64-msvc": "1.1.5" + "@rolldown/binding-android-arm64": "1.2.1", + "@rolldown/binding-darwin-arm64": "1.2.1", + "@rolldown/binding-darwin-x64": "1.2.1", + "@rolldown/binding-freebsd-x64": "1.2.1", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.1", + "@rolldown/binding-linux-arm64-gnu": "1.2.1", + "@rolldown/binding-linux-arm64-musl": "1.2.1", + "@rolldown/binding-linux-ppc64-gnu": "1.2.1", + "@rolldown/binding-linux-s390x-gnu": "1.2.1", + "@rolldown/binding-linux-x64-gnu": "1.2.1", + "@rolldown/binding-linux-x64-musl": "1.2.1", + "@rolldown/binding-openharmony-arm64": "1.2.1", + "@rolldown/binding-wasm32-wasi": "1.2.1", + "@rolldown/binding-win32-arm64-msvc": "1.2.1", + "@rolldown/binding-win32-x64-msvc": "1.2.1" } }, "node_modules/router": { @@ -3567,35 +1937,12 @@ "node": ">= 18" } }, - "node_modules/rxjs": { - "version": "7.8.2", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", - "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.1.0" - } - }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/send": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", @@ -3747,29 +2094,6 @@ "dev": true, "license": "ISC" }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/source-map": { - "version": "0.7.6", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", - "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">= 12" - } - }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -3803,19 +2127,6 @@ "dev": true, "license": "MIT" }, - "node_modules/strip-final-newline": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz", - "integrity": "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -3824,9 +2135,9 @@ "license": "MIT" }, "node_modules/tinyexec": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz", - "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz", + "integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==", "dev": true, "license": "MIT", "engines": { @@ -3851,9 +2162,9 @@ } }, "node_modules/tinyrainbow": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", - "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz", + "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==", "dev": true, "license": "MIT", "engines": { @@ -3869,32 +2180,13 @@ "node": ">=0.6" } }, - "node_modules/tree-kill": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", - "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", - "dev": true, - "license": "MIT", - "bin": { - "tree-kill": "cli.js" - } - }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "dev": true, - "license": "0BSD" - }, - "node_modules/tunnel": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", - "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6.11 <=0.7.0 || >=0.7.3" - } + "license": "0BSD", + "optional": true }, "node_modules/type-is": { "version": "2.1.0", @@ -3927,69 +2219,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/typed-inject": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/typed-inject/-/typed-inject-5.0.0.tgz", - "integrity": "sha512-0Ql2ORqBORLMdAW89TQKZsb1PQkFGImFfVmncXWe7a+AA3+7dh7Se9exxZowH4kbnlvKEFkMxUYdHUpjYWFJaA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/typed-rest-client": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-2.3.1.tgz", - "integrity": "sha512-k4kX5Up6qA68D0Cby2AK+6+vM5k3qTxe+/3FqhnHRExjY5cfbOnzjQZbP/LXleF8hVoDvDqxlgk9KK83HoBZlQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "des.js": "^1.1.0", - "js-md4": "^0.3.2", - "qs": "6.15.1", - "tunnel": "0.0.6", - "underscore": "^1.13.8" - }, - "engines": { - "node": ">= 16.0.0" - } - }, - "node_modules/typed-rest-client/node_modules/qs": { - "version": "6.15.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.1.tgz", - "integrity": "sha512-6YHEFRL9mfgcAvql/XhwTvf5jKcOiiupt2FiJxHkiX1z4j7WL8J/jRHYLluORvc1XxB5rV20KoeK00gVJamspg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/underscore": { - "version": "1.13.8", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz", - "integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/unicorn-magic": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", - "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -3999,37 +2228,6 @@ "node": ">= 0.8" } }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -4040,16 +2238,16 @@ } }, "node_modules/vite": { - "version": "8.1.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.5.tgz", - "integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==", + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.0.tgz", + "integrity": "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==", "dev": true, "license": "MIT", "dependencies": { - "lightningcss": "^1.32.0", + "lightningcss": "^1.33.0", "picomatch": "^4.0.5", - "postcss": "^8.5.17", - "rolldown": "~1.1.5", + "postcss": "^8.5.23", + "rolldown": "~1.2.0", "tinyglobby": "^0.2.17" }, "bin": { @@ -4066,7 +2264,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.3.0", + "@vitejs/devtools": "^0.4.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -4207,13 +2405,6 @@ } } }, - "node_modules/weapon-regex": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/weapon-regex/-/weapon-regex-1.3.6.tgz", - "integrity": "sha512-wsf1m1jmMrso5nhwVFJJHSubEBf3+pereGd7+nBKtYJ18KoB/PWJOHS3WRkwS04VrOU0iJr2bZU+l1QaTJ+9nA==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -4252,26 +2443,6 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/yoctocolors": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.2.0.tgz", - "integrity": "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/zod": { "version": "3.25.76", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", diff --git a/mcp/package.json b/mcp/package.json index d72b57f..62afb79 100644 --- a/mcp/package.json +++ b/mcp/package.json @@ -11,16 +11,13 @@ }, "scripts": { "start": "node src/index.js", - "test": "vitest run", - "mutation:test": "stryker run" + "test": "vitest run" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.0.4", "zod": "^3.23.8" }, "devDependencies": { - "@stryker-mutator/core": "^9.6.1", - "@stryker-mutator/vitest-runner": "^9.6.1", "vitest": "^4.1.10" } } diff --git a/mcp/src/state.js b/mcp/src/state.js index bf26a2d..5f67c47 100644 --- a/mcp/src/state.js +++ b/mcp/src/state.js @@ -40,6 +40,12 @@ function resolveUid() { reloadDb() if (_db.users.length === 1) return _db.users[0].id if (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`) + // Multiple users in db.json but no state files yet — list their ids, not the (empty) + // files list. Hit when accounts exist but none has signed in on a device. + throw new Error( + `multiple openGym users found — set OPENGYM_UID to one of: ${_db.users.map(u => u.id).join(', ')}\n` + + ` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)` + ) } throw new Error( `multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` + diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 517713a..552bf79 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -4,7 +4,7 @@ import { z } from 'zod' import { getState, getUser } from './state.js' import { - fmt, setLabel, exLine, muscleName, policyName, friendlyDate, friendlyDuration, ratio, muscleOrder + setLabel, exLine, muscleName, policyName, friendlyDuration, ratio, muscleOrder } from './labels.js' import { modeOf, workoutVolume, setsDone, effectiveRoutine, effectiveRoutineId @@ -13,21 +13,17 @@ import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js' import { estimate1RM, best1RM, e1rmSeries, FORMULAS, DEFAULT_FORMULA, REP_CAP } from '../../frontend/src/lib/onerm.js' -import { loadOfWorkouts, rankOf, levelsOf, MUSCLES } from '../../frontend/src/lib/muscles.js' +import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js' /* ---------- helpers ---------- */ -const ISO = /^\d{4}-\d{2}-\d{2}$/ -function requireIso(v, name) { - const s = typeof v === 'string' ? v : '' - if (s && !ISO.test(s)) throw new Error(`${name} must be YYYY-MM-DD (got ${JSON.stringify(v)})`) - return s || null -} - -// Drops ISO dates so an LLM passing 'yesterday' is rejected. function entryView(e, S) { const ex = exOr(e.id) - const mode = modeOf(e.target || { id: e.id }) + // Spread id into the cfg the way every call site in the app does (Workout.jsx, Stats.jsx, + // progression.js) — the sheet saves a cardio target as {sets, min, speed} with no id and no + // mode, so modeOf needs the id to fall through to isCardio(id). + const cfg = { ...(e.target || {}), id: e.id } + const mode = modeOf(cfg) return { id: e.id, name: ex.n, @@ -36,7 +32,7 @@ function entryView(e, S) { target: e.target || null, sets: (e.sets || []).map(s => ({ done: !!s.done, - label: setLabel(e.id, { ...s, done: undefined }, e.target || { id: e.id }), + label: setLabel(e.id, { ...s, done: undefined }, cfg), w: Number(s.w) || 0, r: Number(s.r) || 0, sec: Number(s.sec) || 0, @@ -279,7 +275,7 @@ export const estimate1rm = { name: 'estimate_1rm', description: `Estimate one-rep max using Epley, Brzycki or Lombardi formulas. If an exercise_id is given, returns the all-time best estimate for that exercise with the source set (weight × reps + date) and the trend across history. If no exercise_id is given, returns a PR table across all reps-mode exercises (sorted highest first). Refuses to guess above ${REP_CAP} reps — above that, formulas diverge past 10% and "work capacity" is read instead of "maximal strength".`, schema: { - exercise_id: z.string().optional().describe('An exercise id from list_routines, get_workout entries, or search_exercises (v1.5). If omitted, returns a full PR table.'), + exercise_id: z.string().optional().describe('An exercise id from list_routines or get_workout entries. If omitted, returns a full PR table.'), formula: z.enum(['epley', 'brzycki', 'lombardi']).optional().describe(`Formula to use. Defaults to ${DEFAULT_FORMULA}.`) }, handler: ({ exercise_id, formula }) => { diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 491aca0..3002bc8 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -4,6 +4,7 @@ // (rest-day override, missing routine, zero-workout history, no synced state, superset links). import { describe, beforeAll, afterAll, beforeEach, test, expect, vi } from 'vitest' import { buildDemoState } from '../../frontend/src/lib/demoSeed.js' +import { EXDB } from '../../frontend/src/lib/exercises.js' import { _seedStateForTests } from '../src/state.js' import { TOOLS } from '../src/tools.js' @@ -281,6 +282,23 @@ describe('get_workout', () => { expect(w.entries[2].sets[0].label).toBe('1:30 · 20') // weighted plank expect(w.entries[3].sets[0].label).toBe('20 min @ 8 km/h') // cardio }) + + test('infers cardio mode from the exercise id when the target has no mode key', () => { + // Reproduces the review bug: the sheet saves a cardio target as {sets, min, speed} with + // no mode and no id. modeOf must fall through to isCardio(id), which needs the id on the + // cfg — entryView has to spread id into the cfg the way every app call site does. + const CARDIO_ID = EXDB.find(e => e.bp === 'cardio').id + S.workouts = [{ + id: 'synth-cardio', d: '2026-07-25', start: 0, end: 1800000, routineId: 'x', name: 'Synth', + bw: 78, vol: 0, prs: [], + entries: [ + { id: CARDIO_ID, target: { sets: 1, min: 20, speed: 8 }, sets: [{ min: 20, speed: 8, done: true }] } + ] + }] + const w = call('get_workout', { date: '2026-07-25' }) + expect(w.entries[0].mode).toBe('cardio') + expect(w.entries[0].sets[0].label).toBe('20 min @ 8 km/h') + }) }) /* ---------- get_bodyweight ---------- */ From ba412cb36dd7e94d27f3e802186cf8ab05fc4359 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 4 Aug 2026 16:30:34 +0200 Subject: [PATCH 06/58] MCP: die Lib bleibt unter reinem Node ladbar, und die Testwerte stimmen wieder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Der MCP-Server ist ein nacktes `node src/index.js` — kein Vite, kein React. PR 19 hatte dafuer den reinen Kern nach i18n-core.js gezogen; v1.2.4 hat danach in history.js `t` wieder aus i18n.js geholt, und damit import.meta.glob ueber die Locale-Packs plus useSyncExternalStore in einen Prozess, der beides nicht hat. Der Server starb beim Import: TypeError: (intermediate value).glob is not a function Die Testsuite konnte das nicht sehen: vitest transformiert import.meta.glob, also liefen 33 gruene Tests gegen ein Binary, das nie startet. i18n.js re-exportiert ohnehin genau dieses `t` aus dem Kern — history.js, mobile.js und plan-share.js holen es jetzt direkt von dort, und mitgeschleppt wird nichts mehr. Dazu die Werte, die der v1.2.4-Seed verschoben hat: Volumen 18500 → 18412.5 (Handsumme w×r ueber die zwanzig erledigten Saetze), Koerpergewicht 78.6 → 78.4, Wiegung 78.5/1.5 → 78.3/1.3, Dauer 51 min → 1h 11m — samt der Zusicherung, die sich das "N min"-Format noch fest verdrahtet hatte. Jeder Wert nachgerechnet, nicht aus einem roten Lauf abgeschrieben. Und das FORMULAS aus Punkt 2 des Reviews, das als einziges stehengeblieben war. --- frontend/src/lib/history.js | 6 +++++- frontend/src/lib/mobile.js | 2 +- frontend/src/lib/plan-share.js | 2 +- mcp/src/tools.js | 2 +- mcp/test/tools.test.js | 11 ++++++++--- 5 files changed, 16 insertions(+), 7 deletions(-) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index c63b942..2fe59d0b 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -1,7 +1,11 @@ // Pure helpers over the state object S (ported 1:1 from the vanilla app). import { todayISO, isoOf, weekKey, fmtNum } from './format.js' import { isCardio, isBodyweightEq } from './exercises.js' -import { t } from './i18n.js' +// i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no +// React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore +// for the hook — and it re-exports this very `t` from core, so nothing changes here except what +// gets dragged along behind it. +import { t } from './i18n-core.js' // How an exercise is logged (issue #16). This used to be derived from the body part alone, // which meant a plank or a farmer's carry could only be timed by filing it under cardio. diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js index 0e6eb80..a337abb 100644 --- a/frontend/src/lib/mobile.js +++ b/frontend/src/lib/mobile.js @@ -9,7 +9,7 @@ // // Like the demo build, MOBILE is replaced at build time, so all of this folds away in // web bundles; the Capacitor plugins are only ever imported behind it. -import { t } from './i18n.js' +import { t } from './i18n-core.js' export const MOBILE = import.meta.env.VITE_MOBILE === '1' diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js index c04acd1..7e41d1d 100644 --- a/frontend/src/lib/plan-share.js +++ b/frontend/src/lib/plan-share.js @@ -11,7 +11,7 @@ import { EXIDX, isBodyweightEq } from './exercises.js' import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js' import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js' -import { t } from './i18n.js' +import { t } from './i18n-core.js' const PLAN_FMT = 1 const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 552bf79..286755b 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -11,7 +11,7 @@ import { } from '../../frontend/src/lib/history.js' import { EXIDX, exOr } from '../../frontend/src/lib/exercises.js' import { - estimate1RM, best1RM, e1rmSeries, FORMULAS, DEFAULT_FORMULA, REP_CAP + estimate1RM, best1RM, e1rmSeries, DEFAULT_FORMULA, REP_CAP } from '../../frontend/src/lib/onerm.js' import { loadOfWorkouts, rankOf, levelsOf } from '../../frontend/src/lib/muscles.js' diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 3002bc8..6253952 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -12,8 +12,11 @@ import { TOOLS } from '../src/tools.js' // the demo state's exact values. const FAKE_TODAY_ISO = '2026-07-27' // Monday — Push Day is scheduled const GOAL_WEIGHT = 77 -const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18500, bw: 78.6, sets_done: 20, sets_total: 20, duration_min: 51 } -const LATEST_BW = { date: '2026-07-27', weight: 78.5, delta: 1.5 } +// Re-pinned against the v1.2.4 seed, which moved when the demo learned about bodyweight work +// and effort. Hand-checked rather than copied off a failing run: 18412.5 is the sum of w×r +// over the twenty completed sets, and 1.3 is 78.3 − 77. +const NEWEST_WORKOUT = { date: '2026-07-24', name: 'Leg Day', volume: 18412.5, bw: 78.4, sets_done: 20, sets_total: 20, duration: '1h 11m' } +const LATEST_BW = { date: '2026-07-27', weight: 78.3, delta: 1.3 } const LEG_PRESS_ID = '0739' // sled 45° leg press in the demo data const LEG_PRESS_BEST = { w: 152.5, r: 12, epley: 213.5, brzycki: 219.6 } @@ -207,7 +210,9 @@ describe('list_workouts', () => { expect(r.workouts[0].sets_done).toBe(NEWEST_WORKOUT.sets_done) expect(r.workouts[0].sets_planned).toBe(NEWEST_WORKOUT.sets_total) expect(r.workouts[0].sets_ratio).toBe(`${NEWEST_WORKOUT.sets_done}/${NEWEST_WORKOUT.sets_total}`) - expect(r.workouts[0].duration).toBe(`${NEWEST_WORKOUT.duration_min} min`) + // Past the hour the lib switches format, so the expectation carries the rendered string + // rather than assuming a "N min" shape that only held while the session was shorter. + expect(r.workouts[0].duration).toBe(NEWEST_WORKOUT.duration) expect(r.workouts[0].bodyweight_at_workout).toBe(NEWEST_WORKOUT.bw) r.workouts.forEach(w => { expect(w.sets_done).toBeLessThanOrEqual(w.sets_planned) From e28345dd13c7a39a8c0551090946480b2d91fbdd Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 4 Aug 2026 16:35:34 +0200 Subject: [PATCH 07/58] Release v1.2.5: der MCP-Server, und sonst nichts an der App MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Letztes publiziertes Release war v1.2.4, also ist das hier v1.2.5 — alles seit dem Release in EINE Nummer. Inhalt ist genau eine Sache: der optionale MCP-Server aus PR #19 nebst dem i18n-Kern-Split, der ihn ueberhaupt erst unter reinem Node ladbar macht. An der App selbst aendert sich nichts. Wer keinen KI-Client benutzt, merkt von diesem Release ueberhaupt nichts: nichts wandert in den Docker-Build, die docker-compose.yml bleibt unberuehrt. Kein neues APK — der Bundle-Hash bewegt sich zwar (der Modulgraph haengt jetzt direkt am i18n-Kern), aber verhalten tut sich die App identisch. Die Download-Zeile auf der Website bleibt deshalb bei v1.2.4. --- CHANGELOG.md | 39 +++++++++++++++++++++++++++++++ README.md | 1 + api/package.json | 2 +- frontend/android/app/build.gradle | 4 ++-- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- 6 files changed, 46 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f06387..58486ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,44 @@ # Changelog +## v1.2.5 — 2026-08-04 + +Nothing in the app itself changed. This release adds an optional side door: a small server that +lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about +your own training, off the same files your instance already writes. If you don't use one, this +release is invisible to you. + +### Ask an AI about your training, without the data leaving your box (#19) + +- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM + client spawns it as a local process, it reads `./data` directly, and it exits when the client + disconnects. No new container, no extra auth on the api, no third-party service, nothing over + the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which + muscles have I been neglecting?"* +- **The answers match the Stats screen because they are the same numbers.** The server calls the + very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing + them. Eight tools: routines, the week plan, workouts, one session in detail, body weight, + estimated 1RM and muscle balance. +- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api + does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the + server answers questions and does nothing else. It never reads passkey material, VAPID keys or + session state — only the profile it was pointed at. +- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores + this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md). + +### Under the hood + +- The pure half of `i18n.js` — the language state, the constants, the readers — moved into + `i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process + and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React + hook) and re-exports the rest, so nothing that imports it had to change. +- The shared lib modules that only need `t` now take it from the core directly. A Vite-only + import inside a shared module is invisible under vitest, which transforms it, and fatal to the + MCP server, which does not — so the shared half stays clear of the bundler half by + construction rather than by remembering to. + +The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in +openGym written by someone other than me. Thank you. + ## v1.2.4 — 2026-08-01 The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight diff --git a/README.md b/README.md index c8d8893..cfff491 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast - 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped - 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry** +- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there - 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch)) ## Quick start (self-host) diff --git a/api/package.json b/api/package.json index bac7b39..ba14e46 100644 --- a/api/package.json +++ b/api/package.json @@ -1,6 +1,6 @@ { "name": "gym-api", - "version": "1.2.4", + "version": "1.2.5", "private": true, "type": "module", "main": "server.js", diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle index ecd76b2..0b58287 100644 --- a/frontend/android/app/build.gradle +++ b/frontend/android/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "ch.duartesantos.opengym" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 5 - versionName "1.2.4" + versionCode 6 + versionName "1.2.5" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 4be4005..7ca26e4 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengym-frontend", - "version": "1.2.4", + "version": "1.2.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengym-frontend", - "version": "1.2.4", + "version": "1.2.5", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/core": "^7.6.8", diff --git a/frontend/package.json b/frontend/package.json index 452bd6c..b8b70ca 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "opengym-frontend", "private": true, - "version": "1.2.4", + "version": "1.2.5", "type": "module", "scripts": { "dev": "vite", From e007f76d432ce5ca1ba3f12aa0e4e56928545d9d Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 4 Aug 2026 16:40:03 +0200 Subject: [PATCH 08/58] MCP: CI laeuft ueberhaupt erstmal, und der Server ueberlebt seinen Client nicht MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fuer mcp/ gab es keinen CI-Job — weder die 33 Tests noch sonst irgendwas lief je auf GitHub. Jetzt laeuft beides bei jedem PR, der mcp/ oder frontend/ anfasst. Dazu der Check, den die Testsuite prinzipiell nicht machen kann: vitest loest ueber Vite auf, also gehen dort import.meta.glob, ?raw und .jsx anstandslos durch. Genau so kam ein Vite-only-Import in ein gemeinsames Lib-Modul und liess 33 gruene Tests ueber einem Server stehen, der beim Start starb. check-node-loadable.mjs laeuft deshalb unter nacktem node — dass es ausserhalb von vitest laeuft, IST der Test. Gegengeprueft: Bug wieder eingebaut → Exit 1 und history.js/progression.js/tools.js namentlich gemeldet; sauber → Exit 0. Und der fs.watch-Handle haelt die Event-Loop offen, sobald es eine State-Datei zu beobachten gibt — der Prozess ueberlebt damit den Client, der ihn gestartet hat, obwohl die mcp/README genau das Gegenteil verspricht. Ein unref() reicht; nachgemessen: mit State-Datei vorher Exit 124 (haengt), jetzt Exit 0, und der Watcher invalidiert den Cache unveraendert weiter. --- .github/workflows/test.yml | 22 ++++++++++++ CHANGELOG.md | 3 ++ mcp/package.json | 5 +-- mcp/scripts/check-node-loadable.mjs | 55 +++++++++++++++++++++++++++++ mcp/src/state.js | 6 ++++ 5 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 mcp/scripts/check-node-loadable.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4e3af34..e8632b4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,11 +6,13 @@ on: pull_request: paths: - 'frontend/**' + - 'mcp/**' - '.github/workflows/test.yml' push: branches: [main] paths: - 'frontend/**' + - 'mcp/**' - '.github/workflows/test.yml' workflow_dispatch: @@ -41,3 +43,23 @@ jobs: working-directory: frontend - run: node scripts/check-locales.mjs working-directory: frontend + + mcp: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 22 + cache: npm + cache-dependency-path: mcp/package-lock.json + - run: npm ci + working-directory: mcp + - run: npm test + working-directory: mcp + # The one check the vitest suite structurally cannot make. The MCP server is a bare node + # process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and + # ?raw all resolve happily there. That is how a Vite-only import reached a shared lib + # module with 33 green tests standing over a server that died on startup. + - run: npm run check:node-loadable + working-directory: mcp diff --git a/CHANGELOG.md b/CHANGELOG.md index 58486ab..78539f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,9 @@ release is invisible to you. import inside a shared module is invisible under vitest, which transforms it, and fatal to the MCP server, which does not — so the shared half stays clear of the bundler half by construction rather than by remembering to. +- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`, + which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the + MCP tests — neither had ever run there before. The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in openGym written by someone other than me. Thank you. diff --git a/mcp/package.json b/mcp/package.json index 62afb79..92e3de6 100644 --- a/mcp/package.json +++ b/mcp/package.json @@ -3,7 +3,7 @@ "version": "0.1.0", "private": true, "type": "module", - "description": "MCP (Model Context Protocol) bridge for openGym — lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.", + "description": "MCP (Model Context Protocol) bridge for openGym \u2014 lets an external LLM read your routines, workouts, body-weight log, estimated 1RMs and muscle balance from your self-hosted data. Read-only, stdio transport; no extra container.", "license": "AGPL-3.0-or-later", "main": "src/index.js", "bin": { @@ -11,7 +11,8 @@ }, "scripts": { "start": "node src/index.js", - "test": "vitest run" + "test": "vitest run", + "check:node-loadable": "node scripts/check-node-loadable.mjs" }, "dependencies": { "@modelcontextprotocol/sdk": "^1.0.4", diff --git a/mcp/scripts/check-node-loadable.mjs b/mcp/scripts/check-node-loadable.mjs new file mode 100644 index 0000000..4400c6e --- /dev/null +++ b/mcp/scripts/check-node-loadable.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node +/* Does the server's import graph still load under plain node? + * + * This exists because the test suite cannot answer that question. `npm test` runs vitest, and + * vitest resolves modules through Vite — `import.meta.glob`, `?raw`, a stray `.jsx` import all + * work there. The server does not run under Vite. So a Vite-only import can land in a shared + * lib module, leave all 33 tests green, and still kill the server at startup. That is exactly + * what happened once: `history.js` began importing `t` from `i18n.js` (import.meta.glob over + * the locale packs, plus React), and the server died on `import` with the suite none the wiser. + * + * Run by bare `node` on purpose — being outside vitest IS the check. Do not port this to a + * vitest test file; that would make it pass unconditionally. + * + * Importing the two entry modules is enough on its own: everything the server touches hangs off + * them, so a lib module that grows a browser-only dependency next year fails here without this + * list being updated. The named list below only exists to point at the culprit instead of at a + * stack trace ten frames deep. + */ +const LIB = new URL('../../frontend/src/lib/', import.meta.url) + +// Every frontend/src/lib module the server reaches today. Named individually so a failure says +// which one, rather than which import chain. +const MODULES = [ + 'i18n-core.js', 'format.js', 'exercises.js', 'exercises-data.js', + 'history.js', 'muscles.js', 'onerm.js', 'progression.js' +] + +let failed = 0 +for (const m of MODULES) { + try { + await import(new URL(m, LIB)) + console.log(` ok ${m}`) + } catch (e) { + failed++ + console.error(` FAIL ${m} — ${e.message}`) + } +} + +// The real assertion: the server's own entry points, which pull the whole graph transitively. +// A module added to the graph later is covered by this even if the list above never learns it. +for (const entry of ['../src/state.js', '../src/tools.js']) { + try { + await import(new URL(entry, import.meta.url)) + console.log(` ok mcp/${entry.replace('../', '')}`) + } catch (e) { + failed++ + console.error(` FAIL mcp/${entry.replace('../', '')} — ${e.message}`) + } +} + +if (failed) { + console.error(`\n${failed} module(s) do not load under plain node — the MCP server would not start.`) + process.exit(1) +} +console.log('\nthe whole MCP import graph loads under plain node.') diff --git a/mcp/src/state.js b/mcp/src/state.js index 5f67c47..72c2b03 100644 --- a/mcp/src/state.js +++ b/mcp/src/state.js @@ -75,6 +75,12 @@ export function init() { _state = undefined _loadedMtime = 0 }) + // Unref'd, or the watcher alone holds the event loop open and the process outlives the + // client that spawned it — "exits when the LLM client disconnects" stops being true the + // moment there is a state file to watch. Most clients kill the child anyway, but one that + // merely closes the pipe would leak a process per session. Watching is unaffected: the + // stdio transport is what keeps the loop alive while a client is actually attached. + _watcher.unref() } catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ } } From 551b072c540ecdd41e5042ba0817c63c949a4e90 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 4 Aug 2026 17:48:52 +0200 Subject: [PATCH 09/58] MCP: die zweite Einheit an einem Tag ist erreichbar, und ein leeres 1RM sagt warum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Zwei Befunde aus dem Parity-Durchlauf gegen echte Daten. Die Arithmetik stimmte ueberall (rund 120 Werte gegen eine unabhaengige Nachrechnung, null Abweichung) — diese beiden nicht. get_workout nahm `.find(x => x.d === date)`. Wer morgens hebt und abends laeuft, hat zwei Einheiten am selben Datum, und die zweite war ueber gar keinen Weg erreichbar: es gab nirgends eine id, und die Frage nach dem Lauf bekam die Zahlen des Zugtrainings — vollkommen selbstbewusst vorgetragen. list_workouts liefert jetzt `id`, get_workout nimmt `workout_id` oder `date`, und bei zwei Treffern am selben Tag antwortet es mit beiden zur Auswahl statt zu raten. Und `best: null` hatte zwei gegensaetzliche Ursachen in einer Form: nie trainiert, oder immer ueber der 12-Wiederholungs-Grenze. Eine Wade, die seit Monaten mit 15ern im Log steht, las sich damit als "keine Aufzeichnungen". no_estimate_reason unterscheidet die beiden, und formula_note steht jetzt auch auf diesem Zweig — bisher gab es die Erklaerung nur in der PR-Tabelle. Drei Regressionstests dazu (36 statt 33), mcp/README zu get_workout nachgezogen. --- mcp/README.md | 2 +- mcp/src/tools.js | 54 ++++++++++++++++++++++++++++++++++++++---- mcp/test/tools.test.js | 54 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 6 deletions(-) diff --git a/mcp/README.md b/mcp/README.md index 77b2641..0cff276 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -75,7 +75,7 @@ Eight read-only tools in v1: | `get_routine` | What does the Push Day routine prescribe? (sets/reps/weight per exercise) | | `get_week_plan` | What's on my plan this week, including today with any date-specific override? | | `list_workouts` | Recent sessions — newest first, with dates, sets done/planned, volume, duration, PRs. | -| `get_workout` | Full set-by-set breakdown of one date's session. | +| `get_workout` | Full set-by-set breakdown of one session, by `workout_id` or by date. On a day with two sessions the date alone returns both ids to pick from rather than guessing at one. | | `get_bodyweight` | Weigh-ins with the latest weight, the goal line, and deltas vs goal. | | `estimate_1rm` | All-time best 1RM for an exercise + the trend, or a PR table across all exercises. | | `muscle_balance` | Which muscles I've trained this week/month/all-time, ranked + which I've neglected. | diff --git a/mcp/src/tools.js b/mcp/src/tools.js index 286755b..edf77c5 100644 --- a/mcp/src/tools.js +++ b/mcp/src/tools.js @@ -189,6 +189,10 @@ export const listWorkouts = { total_count: all.length, returned_count: filtered.length, workouts: filtered.map(w => ({ + // The only thing that identifies a session uniquely. Two workouts on one day is + // ordinary — a lifting session and an evening run — and without an id here the second + // one cannot be asked about at all. + id: w.id || null, date: w.d, routine_id: w.routineId || null, routine_name: w.name || null, @@ -215,14 +219,44 @@ function plannedSets(w) { /** get_workout — full entry/set breakdown for one date. */ export const getWorkout = { name: 'get_workout', - description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Use list_workouts first if you don\'t know the exact date.', - schema: { date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe('The workout date as YYYY-MM-DD') }, - handler: ({ date }) => { + description: 'Get the full breakdown of one workout: every exercise, its mode (reps/time/cardio), the target, and per-set labels (e.g. "5 @ 60 kg", "1:30 · 20 kg"). Identify it by workout_id (from list_workouts) or by date. Use list_workouts first if you don\'t know either.', + schema: { + date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe('The workout date as YYYY-MM-DD. If two sessions share that date, the answer lists them instead and asks for a workout_id.'), + workout_id: z.string().min(1).optional().describe('The id from list_workouts. Preferred: it names one session even on a day with two.') + }, + handler: ({ date, workout_id }) => { const S = getState() if (!S) return noState() - const w = (S.workouts || []).find(x => x.d === date) - if (!w) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e } + const workouts = S.workouts || [] + let w + if (workout_id) { + w = workouts.find(x => x.id === workout_id) + if (!w) { const e = new Error(`no workout with id ${workout_id}`); e.code = 'ENOENT'; throw e } + } else if (date) { + const sameDay = workouts.filter(x => x.d === date) + if (!sameDay.length) { const e = new Error(`no workout on ${date}`); e.code = 'ENOENT'; throw e } + // Answering with the first of two is how a question about the evening run gets the + // morning's lifting numbers, stated with total confidence. Say there are two instead. + if (sameDay.length > 1) { + return { + ambiguous: true, + date, + message: `${sameDay.length} workouts were logged on ${date} — call get_workout again with one of these workout_id values.`, + workouts: sameDay.map(x => ({ + id: x.id || null, + routine_name: x.name || null, + sets_done: setsDone(x), + volume: workoutVolume(x), + duration: x.end && x.start ? friendlyDuration(x.end - x.start) : null + })) + } + } + w = sameDay[0] + } else { + const e = new Error('get_workout needs either workout_id or date'); e.code = 'EINVAL'; throw e + } return { + id: w.id || null, date: w.d, routine_id: w.routineId || null, routine_name: w.name || null, @@ -286,11 +320,21 @@ export const estimate1rm = { const ex = exOr(exercise_id) const best = best1RM(S, exercise_id, f) const series = e1rmSeries(S, exercise_id, f) + // A null best has two very different causes: never trained, or trained only above the + // rep cap. Without saying which, an exercise logged for years at 15 reps reads as "no + // records for calf raise" — a confident statement about the opposite of the truth. + const trainedAtAll = (S.workouts || []).some(w => + (w.entries || []).some(e => e.id === exercise_id && (e.sets || []).some(s => s.done))) // w/r (not weight/reps) matches pr_table and entry-view — every set in the API surface uses the same couple. return { exercise: { id: exercise_id, name: ex.n, body_part: ex.bp || null }, formula: f, + formula_note: `Estimates use the ${f} formula. Cap at ${REP_CAP} reps applies; r=1 is treated as the measurement, not an estimate.`, best: best ? { est: best.est, w: best.w, r: best.r, date: best.d } : null, + no_estimate_reason: best ? null + : trainedAtAll + ? `This exercise has logged sets, but none of them qualify: every set was above the ${REP_CAP}-rep cap, or carried no weight. That is not the same as never having trained it.` + : 'No completed sets logged for this exercise.', trend: series.map(p => ({ date: p.d, est: p.y, w: p.w, r: p.r })) } } diff --git a/mcp/test/tools.test.js b/mcp/test/tools.test.js index 6253952..17f2c70 100644 --- a/mcp/test/tools.test.js +++ b/mcp/test/tools.test.js @@ -267,6 +267,32 @@ describe('get_workout', () => { expect(() => call('get_workout', { date: '1900-01-01' })).toThrow() }) + test('two sessions on one day are both reachable, and the date alone never picks one silently', () => { + // Lifting in the morning, a run in the evening: ordinary, and it used to make the second + // session unreachable while questions about it were answered with the first one's numbers. + const day = '2026-07-26' + S.workouts.push( + { id: 'w-morning', d: day, name: 'Pull', start: 1000, end: 1000 + 40 * 60000, vol: 0, prs: [], entries: [] }, + { id: 'w-evening', d: day, name: 'Cardio', start: 2000, end: 2000 + 55 * 60000, vol: 0, prs: [], entries: [] } + ) + _seedStateForTests(S) + + const amb = call('get_workout', { date: day }) + expect(amb.ambiguous).toBe(true) + expect(amb.workouts.map(w => w.id).sort()).toEqual(['w-evening', 'w-morning']) + + // Each is retrievable by the id the ambiguous answer handed back. + expect(call('get_workout', { workout_id: 'w-evening' }).routine_name).toBe('Cardio') + expect(call('get_workout', { workout_id: 'w-morning' }).routine_name).toBe('Pull') + // And list_workouts carries the id, or nothing above could ask for one. + expect(call('list_workouts', {}).workouts.every(w => 'id' in w)).toBe(true) + }) + + test('an unknown workout_id is an error, not the wrong workout', () => { + expect(() => call('get_workout', { workout_id: 'nope' })).toThrow() + expect(() => call('get_workout', {})).toThrow() + }) + test('renders reps/time/cardio set labels in the lib format on a synthetic workout', () => { // The starter routine has only reps-mode exercises — synthesise a workout that includes a // timed plank and a cardio row so the label rendering is actually exercised. @@ -389,6 +415,7 @@ describe('estimate_1rm', () => { test('exercises with no reps-mode history get null best + empty trend (not a 0 estimate)', () => { S.workouts = [] + _seedStateForTests(S) const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID }) expect(r.best).toBeNull() expect(r.trend).toEqual([]) @@ -396,6 +423,33 @@ describe('estimate_1rm', () => { expect(table).toEqual([]) }) + test('a null estimate says which kind of null it is', () => { + // "Never trained" and "trained, but always above the rep cap" are opposite facts that both + // arrive as best: null. Undistinguished, the second one reads as the first and an assistant + // reports "no records" for an exercise in the log every week. + S.workouts = [{ + id: 'w-highrep', d: '2026-07-26', name: 'Accessories', start: 1000, end: 1000 + 20 * 60000, + vol: 0, prs: [], + entries: [{ + id: LEG_PRESS_ID, target: { sets: 2, reps: 20, mode: 'reps' }, + sets: [{ w: 40, r: 20, done: true }, { w: 40, r: 18, done: true }] + }] + }] + _seedStateForTests(S) + + const capped = call('estimate_1rm', { exercise_id: LEG_PRESS_ID }) + expect(capped.best).toBeNull() + expect(capped.no_estimate_reason).toMatch(/above the \d+-rep cap/) + + // An exercise that genuinely has no sets must not borrow that explanation. + const never = call('estimate_1rm', { exercise_id: '0684' }) + expect(never.best).toBeNull() + expect(never.no_estimate_reason).toMatch(/No completed sets/) + + // And the cap is stated on this branch at all, which it never used to be. + expect(capped.formula_note).toMatch(/Cap at/) + }) + test('all three formulas are accepted', () => { ['epley', 'brzycki', 'lombardi'].forEach(f => { const r = call('estimate_1rm', { exercise_id: LEG_PRESS_ID, formula: f }) From eeee4b461cb0884cb1efe39c420c6a89a5bbfd18 Mon Sep 17 00:00:00 2001 From: Space-Hermes Date: Thu, 6 Aug 2026 11:33:21 +0200 Subject: [PATCH 10/58] feat: muscle map Fatigue + Strength (detraining) views Per-muscle fatigue (72h window, 36h half-life, .25/.5 bands) and retained strength (14d plateau, 28d half-life, .5 floor) views on the Stats page behind a Balance | Fatigue | Strength segmented control. Pure recovery.js module with fatiguedMuscles/detrainedMuscles hooks, owner-approved backward-compatible absolute-level BodyMap extension, 8 i18n keys across English fallback + 11 locale packs, mounted interaction tests. --- frontend/package-lock.json | 289 ++++++++++++++++++++ frontend/package.json | 1 + frontend/src/components/BodyMap.jsx | 8 +- frontend/src/lib/muscles.js | 28 +- frontend/src/lib/recovery-view.js | 17 ++ frontend/src/lib/recovery-view.test.js | 58 ++++ frontend/src/lib/recovery.js | 188 +++++++++++++ frontend/src/lib/recovery.test.js | 213 +++++++++++++++ frontend/src/locales/de.js | 7 + frontend/src/locales/es.js | 7 + frontend/src/locales/fr.js | 7 + frontend/src/locales/hi.js | 7 + frontend/src/locales/it.js | 7 + frontend/src/locales/ko.js | 7 + frontend/src/locales/pl.js | 7 + frontend/src/locales/pt.js | 7 + frontend/src/locales/ru.js | 7 + frontend/src/locales/tr.js | 7 + frontend/src/locales/zh.js | 7 + frontend/src/views/Stats.jsx | 163 +++++++++-- frontend/src/views/Stats.recovery.test.jsx | 300 +++++++++++++++++++++ 21 files changed, 1307 insertions(+), 35 deletions(-) create mode 100644 frontend/src/lib/recovery-view.js create mode 100644 frontend/src/lib/recovery-view.test.js create mode 100644 frontend/src/lib/recovery.js create mode 100644 frontend/src/lib/recovery.test.js create mode 100644 frontend/src/views/Stats.recovery.test.jsx diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7ca26e4..fbdf56d 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -24,6 +24,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", + "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" } @@ -2594,6 +2595,13 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/cssom": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", + "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", + "dev": true, + "license": "MIT" + }, "node_modules/dargs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", @@ -3337,6 +3345,105 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, + "node_modules/html-escaper": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", + "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/htmlparser2": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", + "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "entities": "^7.0.1" + } + }, + "node_modules/htmlparser2/node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -3826,6 +3933,181 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/linkedom": { + "version": "0.18.13", + "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz", + "integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==", + "dev": true, + "license": "ISC", + "dependencies": { + "css-select": "^7.0.0", + "cssom": "^0.5.0", + "html-escaper": "^3.0.3", + "htmlparser2": "^10.1.0", + "uhyphen": "^0.2.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "canvas": ">= 2" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/linkedom/node_modules/boolbase": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz", + "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/css-select": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz", + "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^2.0.0", + "css-what": "^8.0.0", + "domhandler": "^6.0.1", + "domutils": "^4.0.2", + "nth-check": "^3.0.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/css-what": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz", + "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/dom-serializer": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", + "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==", + "dev": true, + "license": "MIT", + "dependencies": { + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0", + "entities": "^8.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/domelementtype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz", + "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/linkedom/node_modules/domhandler": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz", + "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^3.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/domutils": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz", + "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^3.0.0", + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/entities": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", + "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/nth-check": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz", + "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^2.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", @@ -5886,6 +6168,13 @@ "node": ">=0.8.0" } }, + "node_modules/uhyphen": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz", + "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==", + "dev": true, + "license": "ISC" + }, "node_modules/undici-types": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index b8b70ca..3f58498 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -28,6 +28,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", + "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" } diff --git a/frontend/src/components/BodyMap.jsx b/frontend/src/components/BodyMap.jsx index fe71c47..022f180 100644 --- a/frontend/src/components/BodyMap.jsx +++ b/frontend/src/components/BodyMap.jsx @@ -47,11 +47,13 @@ function View({ view, levels, onMuscle, selected }) { /** * * `load` is effective sets per muscle (see lib/muscles.js); shading is relative to - * the hardest-worked muscle in that same load, so it always reads as a balance. + * the hardest-worked muscle in that same load, so it always reads as a balance. Pass ordered + * `{ at, level, exclusive? }` `thresholds` for a fixed absolute scale (recovery views use this + * to keep their semantic bands stable); omitting it preserves the balance behavior. */ -export default function BodyMap({ load = {}, body = 'male', onMuscle, selected, className = '' }) { +export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle, selected, className = '' }) { const paths = useBodyPaths() - const levels = levelsOf(load) + const levels = levelsOf(load, thresholds) const g = paths && (paths[body] || paths.male) return (
diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index c744812..32db0d9 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -119,11 +119,31 @@ export const loadOfActive = active => loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length }))) /** - * Shade buckets 0–4 per muscle, relative to the hardest-worked muscle in the same - * window. Relative rather than absolute on purpose: the map answers "is my training - * balanced", which only means anything as a comparison within one period. + * Shade buckets 0–4 per muscle. + * + * With no `thresholds`, levels remain relative to the hardest-worked muscle in the same + * window. This is the original balance-map behavior. When `thresholds` is supplied, levels + * use an absolute scale instead: it is an ordered array of `{ at, level, exclusive? }` rules, + * and the last matching rule wins. An exclusive rule matches values strictly greater than + * `at`; otherwise the boundary is inclusive. Values below the first matching rule are l0. + * Absolute rules let recovery views keep fixed semantic bands instead of renormalizing to the + * strongest muscle on screen. */ -export function levelsOf(load) { +export function levelsOf(load, thresholds) { + if (thresholds) { + const lv = {} + MUSCLES.forEach(m => { + const value = Number(load[m] || 0) + let level = 0 + for (const rule of thresholds) { + const matches = rule.exclusive ? value > rule.at : value >= rule.at + if (matches) level = Math.max(0, Math.min(4, rule.level)) + } + lv[m] = level + }) + return lv + } + const max = Math.max(0, ...MUSCLES.map(m => load[m] || 0)) const lv = {} MUSCLES.forEach(m => { diff --git a/frontend/src/lib/recovery-view.js b/frontend/src/lib/recovery-view.js new file mode 100644 index 0000000..1abc6ff --- /dev/null +++ b/frontend/src/lib/recovery-view.js @@ -0,0 +1,17 @@ +import { FATIGUE_STATES } from './recovery.js' + +/** + * Select the consumer-facing fatigue state for one numeric recovery value. + * Values below .25 are ready, .25 through .5 are recovering, and values above .5 are fatigued. + * Keeping this boundary selector in production code prevents views and tests from drifting apart. + * + * @param {number} value Numeric fatigue value from fatigueOf(). + * @returns {'ready'|'recovering'|'fatigued'} The stable state label for the UI. + */ +export function fatigueStateOf(value) { + return value < 0.25 + ? FATIGUE_STATES.READY + : value <= 0.5 + ? FATIGUE_STATES.RECOVERING + : FATIGUE_STATES.FATIGUED +} diff --git a/frontend/src/lib/recovery-view.test.js b/frontend/src/lib/recovery-view.test.js new file mode 100644 index 0000000..6ccc7e6 --- /dev/null +++ b/frontend/src/lib/recovery-view.test.js @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { FATIGUE_STATES, fatigueOf, strengthOf } from './recovery.js' +import { fatigueStateOf } from './recovery-view.js' +import { MUSCLES, levelsOf } from './muscles.js' + +const FATIGUE_BANDS = [ + { at: 0, level: 4 }, + { at: 0.25, level: 2 }, + { at: 0.5, level: 0, exclusive: true }, +] +const STRENGTH_BANDS = [ + { at: 0.5, level: 0 }, + { at: 0.625, level: 1 }, + { at: 0.75, level: 2 }, + { at: 0.875, level: 3 }, + { at: 1, level: 4 }, +] + +describe('production recovery view selectors', () => { + it('preserves the relative balance scale when no thresholds are supplied', () => { + const levels = levelsOf({ chest: 10, biceps: 5 }) + expect(levels.chest).toBe(4) + expect(levels.biceps).toBe(2) + }) + + it('uses the production fatigue selector at both approved boundaries', () => { + expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY) + expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING) + expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING) + expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED) + }) + + it('renders fatigue bands on a fixed absolute scale rather than relative to the map maximum', () => { + const levels = levelsOf({ + chest: 0.25, + biceps: 0.6, + triceps: 0.1, + }, FATIGUE_BANDS) + expect(levels.chest).toBe(2) + expect(levels.biceps).toBe(0) + expect(levels.triceps).toBe(4) + }) + + it('renders strength on fixed .5-to-1 bands with full retention at l4', () => { + const levels = levelsOf({ chest: 0.9, biceps: 1, triceps: 0.5 }, STRENGTH_BANDS) + expect(levels.chest).toBe(3) + expect(levels.biceps).toBe(4) + expect(levels.triceps).toBe(0) + }) + + it('keeps selectors tied to the same render-time clock', () => { + const now = Date.UTC(2026, 0, 22) + const workout = { start: now - 15 * 86400000, d: '2026-01-07', entries: [] } + expect(strengthOf([workout], now).chest).toBe(0.5) + expect(fatigueOf([workout], now).chest).toBe(0) + expect(strengthOf([workout], now + 7 * 86400000).chest).toBe(0.5) + }) +}) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js new file mode 100644 index 0000000..54a2793 --- /dev/null +++ b/frontend/src/lib/recovery.js @@ -0,0 +1,188 @@ +import { EXIDX } from './exercises.js' +import { MUSCLES, musclesOf } from './muscles.js' + +/** Completed-workout window used when calculating current fatigue. */ +export const FATIGUE_WINDOW_MS = 259200000 + +/** Exponential half-life for fatigue stimulus. */ +export const FATIGUE_HALF_LIFE_MS = 129600000 + +/** Period after training during which retained strength remains at full value. */ +export const STRENGTH_FULL_MS = 1209600000 + +/** Exponential half-life for retained strength after the full-retention period. */ +export const STRENGTH_HALF_LIFE_MS = 2419200000 + +/** Minimum retained-strength value for an untrained or fully detrained muscle. */ +export const STRENGTH_FLOOR = 0.5 + +/** + * Stable labels for consumer fatigue buckets: values below 0.25 are ready, values from 0.25 + * through 0.5 are recovering, and values above 0.5 are fatigued. + */ +export const FATIGUE_STATES = Object.freeze({ + READY: 'ready', + RECOVERING: 'recovering', + FATIGUED: 'fatigued', +}) + +/** + * Return exponential decay expressed as a fraction of one half-life. + * + * @param {number} ageMs Elapsed age of the stimulus in milliseconds. + * @param {number} halfLifeMs Duration of one half-life in milliseconds. + * @returns {number} Remaining fraction, using the exact `0.5 ** (age / halfLife)` formula. + */ +export function halfLifeDecay(ageMs, halfLifeMs) { + return 0.5 ** (ageMs / halfLifeMs) +} + +// The v2 data contract has one timestamp per workout, not per set. Keep this fallback in one +// place so fatigue and strength use exactly the same stimulus time as effort.js. +function workoutTimestamp(workout) { + const timestamp = workout?.start || new Date(workout?.d).getTime() + return Number.isFinite(timestamp) ? timestamp : Number(timestamp) +} + +function emptyMuscleMap(value) { + return Object.fromEntries(MUSCLES.map(slug => [slug, value])) +} + +function clamp(value, min, max) { + return Math.min(max, Math.max(min, value)) +} + +// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for +// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while +// preserving the workout/set shape already used by the app. +function completedStimuli(workouts, include) { + const stimuli = [] + for (const workout of workouts || []) { + const timestamp = workoutTimestamp(workout) + if (!Number.isFinite(timestamp) || !include(timestamp)) continue + for (const entry of workout.entries || []) { + const weights = musclesOf(EXIDX[entry.id]) + for (const set of entry.sets || []) { + if (set?.done !== true) continue + for (const [slug, weight] of Object.entries(weights)) { + if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) { + stimuli.push({ slug, timestamp, stimulus: weight }) + } + } + } + } + } + return stimuli +} + +const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true])) + +function fatigueValue(events, now) { + if (!events.length) return 0 + events.sort((a, b) => a.timestamp - b.timestamp) + + let value = 0 + let lastTimestamp = events[0].timestamp + for (const event of events) { + value *= halfLifeDecay(event.timestamp - lastTimestamp, FATIGUE_HALF_LIFE_MS) + value += event.stimulus + lastTimestamp = event.timestamp + } + value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) + return clamp(value, 0, 1) +} + +/** + * Calculate current per-muscle fatigue from completed sets in the recent window. + * + * Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed + * set contributes the exercise's `musclesOf` weights; sets exactly 72 hours old are excluded. + * Stimuli are accumulated chronologically with a 36-hour half-life, decayed to `now`, and + * clamped to [0, 1]. The result always contains every drawable muscle slug. + * + * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. + * @param {number} now Current time in milliseconds; injected to keep this function deterministic. + * @returns {Record} Fatigue values keyed by every drawable muscle slug. + */ +export function fatigueOf(workouts, now) { + const current = Number(now) + const cutoff = current - FATIGUE_WINDOW_MS + const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff) + const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []])) + for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus) + + const result = emptyMuscleMap(0) + if (!Number.isFinite(current)) return result + for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current) + return result +} + +/** + * Calculate retained per-muscle strength from the latest completed stimulus in all history. + * + * A muscle with no completed set starts at the 0.5 floor. After a completed set, strength is + * 1.0 through 14 days old, then decays toward the floor with a 28-day half-life. Any later + * completed set becomes the new latest stimulus and resets the 14-day full-retention period. + * The result always contains every drawable muscle slug. + * + * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. + * @param {number} now Current time in milliseconds; injected to keep this function deterministic. + * @returns {Record} Retained-strength values keyed by every drawable muscle slug. + */ +export function strengthOf(workouts, now) { + const current = Number(now) + const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity])) + const stimuli = completedStimuli(workouts, () => true) + for (const stimulus of stimuli) { + if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp + } + + const result = emptyMuscleMap(STRENGTH_FLOOR) + if (!Number.isFinite(current)) return result + for (const slug of MUSCLES) { + const lastTimestamp = latest[slug] + if (!Number.isFinite(lastTimestamp)) continue + const age = current - lastTimestamp + if (age <= STRENGTH_FULL_MS) { + result[slug] = 1 + } else { + result[slug] = Math.max( + STRENGTH_FLOOR, + halfLifeDecay(age - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS), + ) + } + } + return result +} + +/** + * List muscles currently above the fatigued threshold. + * + * @param {Array} workouts Workout history passed to {@link fatigueOf}. + * @param {number} now Current time in milliseconds passed to {@link fatigueOf}. + * @returns {string[]} Muscle slugs whose fatigue value is greater than 0.5, in `MUSCLES` + * head-to-toe order. + * @example + * const avoid = fatiguedMuscles(workouts, now) + */ +export function fatiguedMuscles(workouts, now) { + return Object.entries(fatigueOf(workouts, now)) + .filter(([, value]) => value > 0.5) + .map(([slug]) => slug) +} + +/** + * List muscles whose retained strength is below full retention. + * + * @param {Array} workouts Workout history passed to {@link strengthOf}. + * @param {number} now Current time in milliseconds passed to {@link strengthOf}. + * @returns {string[]} Muscle slugs whose retained strength is less than 1.0, in `MUSCLES` + * head-to-toe order; never-trained muscles are included at the 0.5 floor. + * @example + * const targets = detrainedMuscles(workouts, now) + */ +export function detrainedMuscles(workouts, now) { + return Object.entries(strengthOf(workouts, now)) + .filter(([, value]) => value < 1) + .map(([slug]) => slug) +} diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js new file mode 100644 index 0000000..2d03dcf --- /dev/null +++ b/frontend/src/lib/recovery.test.js @@ -0,0 +1,213 @@ +import { describe, expect, it } from 'vitest' +import { + FATIGUE_HALF_LIFE_MS, + FATIGUE_STATES, + FATIGUE_WINDOW_MS, + STRENGTH_FLOOR, + STRENGTH_FULL_MS, + STRENGTH_HALF_LIFE_MS, + detrainedMuscles, + fatiguedMuscles, + fatigueOf, + halfLifeDecay, + strengthOf, +} from './recovery.js' +import { EXDB } from './exercises.js' +import { MUSCLES, musclesOf } from './muscles.js' +import { fatigueStateOf } from './recovery-view.js' + +const HOUR = 60 * 60 * 1000 +const DAY = 24 * HOUR +const NOW = Date.UTC(2026, 0, 1, 12) + +// Keep fixtures tied to the shipped catalogue while making the expected stimulus explicit. +const SINGLE = EXDB.find(ex => { + const weights = musclesOf(ex) + return ex.bp !== 'cardio' && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1 +}) +const WEIGHTED = EXDB.find(ex => { + const weights = musclesOf(ex) + return ex.bp !== 'cardio' && Object.values(weights).includes(0.4) +}) +if (!SINGLE || !WEIGHTED) throw new Error('recovery tests require single- and secondary-weight fixtures') + +const SINGLE_WEIGHTS = musclesOf(SINGLE) +const WEIGHTED_WEIGHTS = musclesOf(WEIGHTED) +const SINGLE_SLUG = Object.keys(SINGLE_WEIGHTS)[0] +const WEIGHTED_PRIMARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 1) +const SECONDARY_SLUG = Object.keys(WEIGHTED_WEIGHTS).find(slug => WEIGHTED_WEIGHTS[slug] === 0.4) +if (!WEIGHTED_PRIMARY_SLUG || !SECONDARY_SLUG) throw new Error('recovery tests require weighted primary and secondary fixtures') + +const workoutAt = (id, start, sets = [{ done: true }]) => ({ + d: new Date(start).toISOString(), + start, + entries: [{ id, sets: sets.map(set => ({ ...set })) }], +}) +const doneWorkoutAt = (id, start, count = 1) => + workoutAt(id, start, Array.from({ length: count }, () => ({ done: true }))) +const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0])) +const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR])) + +// Numeric fatigue remains the math API; the UI boundary selector is imported from production. +const stableFloat = value => Number(value.toFixed(12)) + +describe('recovery constants', () => { + it('exports the pinned windows, half-lives, floor, and state labels', () => { + expect(FATIGUE_WINDOW_MS).toBe(72 * HOUR) + expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR) + expect(STRENGTH_FULL_MS).toBe(14 * DAY) + expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY) + expect(STRENGTH_FLOOR).toBe(0.5) + expect(FATIGUE_STATES).toEqual({ READY: 'ready', RECOVERING: 'recovering', FATIGUED: 'fatigued' }) + expect(halfLifeDecay(FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS)).toBe(0.5) + }) +}) + +describe('fatigueOf and strengthOf', () => { + it('returns every muscle, ready/floor defaults, and hook defaults for empty history', () => { + const fatigue = fatigueOf([], NOW) + const strength = strengthOf([], NOW) + + expect(Object.keys(fatigue)).toEqual(MUSCLES) + expect(fatigue).toEqual(zeroFatigue()) + expect(Object.values(fatigue).map(fatigueStateOf)).toEqual( + MUSCLES.map(() => FATIGUE_STATES.READY), + ) + expect(Object.keys(strength)).toEqual(MUSCLES) + expect(strength).toEqual(floorStrength()) + expect(fatiguedMuscles([], NOW)).toEqual([]) + expect(detrainedMuscles([], NOW)).toEqual(MUSCLES) + }) + + it('applies one completed set to each of the exercise muscle weights', () => { + const workouts = [doneWorkoutAt(WEIGHTED.id, NOW)] + const fatigue = fatigueOf(workouts, NOW) + const strength = strengthOf(workouts, NOW) + + for (const slug of MUSCLES) { + const weight = WEIGHTED_WEIGHTS[slug] || 0 + expect(fatigue[slug]).toBe(weight) + expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR) + } + expect(fatiguedMuscles(workouts, NOW)).toEqual( + Object.entries(WEIGHTED_WEIGHTS) + .filter(([, weight]) => weight > 0.5) + .map(([slug]) => slug), + ) + }) + + it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => { + for (const age of [FATIGUE_HALF_LIFE_MS, FATIGUE_HALF_LIFE_MS / 2]) { + const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW) + const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS) + for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) { + expect(fatigue[slug]).toBeCloseTo(weight * expectedDecay, 12) + } + if (age === FATIGUE_HALF_LIFE_MS) expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBe(0.5) + if (age === FATIGUE_HALF_LIFE_MS / 2) { + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(0.5 ** 0.5, 12) + } + } + }) + + it('excludes a completed set exactly at the strict 72-hour window edge', () => { + const workouts = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_WINDOW_MS)] + expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue()) + expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1) + }) + + it('ignores sets whose done flag is false for both axes', () => { + const workouts = [workoutAt(WEIGHTED.id, NOW, [{ done: false }])] + expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue()) + expect(strengthOf(workouts, NOW)).toEqual(floorStrength()) + expect(fatiguedMuscles(workouts, NOW)).toEqual([]) + expect(detrainedMuscles(workouts, NOW)).toEqual(MUSCLES) + }) +}) + +describe('fatigue state boundaries', () => { + it('classifies exactly .25 as recovering and .2499 as ready', () => { + const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG] + const valueAt = target => { + const age = FATIGUE_HALF_LIFE_MS * Math.log2(weight / target) + const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)[SECONDARY_SLUG] + expect(value).toBeCloseTo(target, 10) + return stableFloat(value) + } + + expect(fatigueStateOf(valueAt(0.25))).toBe(FATIGUE_STATES.RECOVERING) + expect(fatigueStateOf(valueAt(0.2499))).toBe(FATIGUE_STATES.READY) + }) + + it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => { + const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS)] + const aboveHalf = [ + doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(1 / 0.5001)), + ] + const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG] + const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG] + + expect(half).toBe(0.5) + expect(fatigueStateOf(half)).toBe(FATIGUE_STATES.RECOVERING) + expect(fatiguedMuscles(atHalf, NOW)).toEqual([]) + expect(above).toBeCloseTo(0.5001, 10) + expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED) + expect(fatiguedMuscles(aboveHalf, NOW)).toEqual([SINGLE_SLUG]) + }) +}) + +describe('strengthOf', () => { + const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG] + + it('stays at full retention through 14 days and decays from 15 days by the 28-day half-life', () => { + expect(strengthAt(STRENGTH_FULL_MS)).toBe(1) + expect(strengthAt(15 * DAY)).toBeCloseTo(0.5 ** (1 / 28), 10) + }) + + it('clamps the 42-day half-life point and later 56-day value at the .5 floor', () => { + expect(strengthAt(42 * DAY)).toBe(0.5) + expect(strengthAt(56 * DAY)).toBe(STRENGTH_FLOOR) + }) + + it('resets retained strength when a later completed session retrains the muscle', () => { + const workouts = [ + doneWorkoutAt(SINGLE.id, NOW - 20 * DAY), + doneWorkoutAt(SINGLE.id, NOW), + ] + expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1) + }) +}) + +describe('accumulation and purity', () => { + it('matches the sum of independently decayed stimuli in chronological order', () => { + const ages = [64 * HOUR, 40 * HOUR] + const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age)) + const expected = ages.reduce( + (sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS), + 0, + ) + + expect(expected).toBeLessThan(1) + expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) + expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) + }) + + it('clamps saturation and returns identical results without mutating inputs or sharing state', () => { + const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)] + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBe(1) + + const workouts = [ + doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR), + doneWorkoutAt(SINGLE.id, NOW - 40 * HOUR), + ] + const before = JSON.parse(JSON.stringify(workouts)) + const firstFatigue = fatigueOf(workouts, NOW) + const firstStrength = strengthOf(workouts, NOW) + const secondFatigue = fatigueOf(workouts, NOW) + const secondStrength = strengthOf(workouts, NOW) + + expect(secondFatigue).toEqual(firstFatigue) + expect(secondStrength).toEqual(firstStrength) + expect(workouts).toEqual(before) + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index d62b7c5d..2ad8876 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -378,6 +378,13 @@ export default { 'Admin dashboard': 'Admin-Dashboard', // --- muscle map --- 'Muscle balance': 'Muskelbalance', + 'Fatigue': 'Ermüdung', + 'Ready': 'Bereit', + 'Recovering': 'In Erholung', + 'Fatigued': 'Ermüdet', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.', + 'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.', + 'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert', 'by sets worked': 'nach Sätzen', 'Week': 'Woche', 'not trained': 'nicht trainiert', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 27c17f0..537af83 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Panel de administración', // --- muscle map --- 'Muscle balance': 'Equilibrio muscular', + 'Fatigue': 'Fatiga', + 'Ready': 'Listo', + 'Recovering': 'En recuperación', + 'Fatigued': 'Fatigado', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.', + 'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.', + 'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.', 'by sets worked': 'por series trabajadas', 'Week': 'Semana', 'not trained': 'sin entrenar', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 9b1de44..e233a3b 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Tableau d’administration', // --- muscle map --- 'Muscle balance': 'Équilibre musculaire', + 'Fatigue': 'Fatigue', + 'Ready': 'Prêt', + 'Recovering': 'En récupération', + 'Fatigued': 'Fatigué', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.', + 'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.', + 'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.', 'by sets worked': 'par séries effectuées', 'Week': 'Semaine', 'not trained': 'non travaillé', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 163cb93..bbf2947 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'एडमिन डैशबोर्ड', // --- muscle map --- 'Muscle balance': 'मांसपेशी संतुलन', + 'Fatigue': 'थकान', + 'Ready': 'तैयार', + 'Recovering': 'पुनर्प्राप्ति में', + 'Fatigued': 'थकी हुई', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।', + 'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।', + 'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले', 'by sets worked': 'सेट के अनुसार', 'Week': 'सप्ताह', 'not trained': 'प्रशिक्षित नहीं', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index af73182..5ccc24b 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Pannello di amministrazione', // --- muscle map --- 'Muscle balance': 'Equilibrio muscolare', + 'Fatigue': 'Fatica', + 'Ready': 'Pronto', + 'Recovering': 'In recupero', + 'Fatigued': 'Affaticato', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.', + 'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.', + 'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa', 'by sets worked': 'per serie svolte', 'Week': 'Settimana', 'not trained': 'non allenato', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index c6a6431..1bcc2bd 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': '관리자 대시보드', // --- muscle map --- 'Muscle balance': '근육 균형', + 'Fatigue': '피로', + 'Ready': '준비됨', + 'Recovering': '회복 중', + 'Fatigued': '피로함', + 'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.', + 'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.', + 'Weeks since training: {0}': '마지막 운동: {0}주 전', 'by sets worked': '세트 수 기준', 'Week': '이번 주', 'not trained': '훈련 안 함', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 5d0fc10..dae273c 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Panel administratora', // --- muscle map --- 'Muscle balance': 'Równowaga mięśniowa', + 'Fatigue': 'Zmęczenie', + 'Ready': 'Gotowe', + 'Recovering': 'W regeneracji', + 'Fatigued': 'Zmęczony', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.', + 'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.', + 'Weeks since training: {0}': 'Trening: {0} tyg. temu', 'by sets worked': 'wg serii', 'Week': 'Tydzień', 'not trained': 'nietrenowane', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index e7e9d0c..a181fe3 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Painel de administração', // --- muscle map --- 'Muscle balance': 'Equilíbrio muscular', + 'Fatigue': 'Fadiga', + 'Ready': 'Pronto', + 'Recovering': 'Em recuperação', + 'Fatigued': 'Fatigado', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.', + 'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.', + 'Weeks since training: {0}': 'Treino: há {0} sem.', 'by sets worked': 'por séries trabalhadas', 'Week': 'Semana', 'not trained': 'sem treino', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 98a9a7c..a3ba4a7 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Панель администратора', // --- muscle map --- 'Muscle balance': 'Баланс мышц', + 'Fatigue': 'Усталость', + 'Ready': 'Готова', + 'Recovering': 'Восстанавливается', + 'Fatigued': 'Утомлена', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.', + 'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.', + 'Weeks since training: {0}': 'Тренировка: {0} нед. назад', 'by sets worked': 'по подходам', 'Week': 'Неделя', 'not trained': 'не тренировалась', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index a5853bf..60c3760 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': 'Yönetici paneli', // --- muscle map --- 'Muscle balance': 'Kas dengesi', + 'Fatigue': 'Yorgunluk', + 'Ready': 'Hazır', + 'Recovering': 'Toparlanıyor', + 'Fatigued': 'Yorgun', + 'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.', + 'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.', + 'Weeks since training: {0}': 'Son antrenman: {0} hafta önce', 'by sets worked': 'çalışılan sete göre', 'Week': 'Hafta', 'not trained': 'çalışılmadı', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 518427a..bf33ba5 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -360,6 +360,13 @@ export default { 'Admin dashboard': '管理后台', // --- muscle map --- 'Muscle balance': '肌肉平衡', + 'Fatigue': '疲劳', + 'Ready': '准备好', + 'Recovering': '恢复中', + 'Fatigued': '已疲劳', + 'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。', + 'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。', + 'Weeks since training: {0}': '上次训练:{0}周前', 'by sets worked': '按训练组数', 'Week': '本周', 'not trained': '未训练', diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index f25b3cd..9da7f0f 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -1,4 +1,4 @@ -import { useState } from 'react' +import { useEffect, useMemo, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { EXIDX } from '../lib/exercises.js' @@ -10,7 +10,9 @@ import LineChart from '../components/LineChart.jsx' import Heatmap from '../components/Heatmap.jsx' import Icon from '../components/Icon.jsx' import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx' -import { loadOfWorkouts, rankOf, MUSCLE_NAME } from '../lib/muscles.js' +import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' +import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js' +import { fatigueStateOf } from '../lib/recovery-view.js' import { e1rmSeries, best1RM } from '../lib/onerm.js' import { hasEffort, displayScale, scaleName, toScale, avgRir, effortSummary, effortWeeks, @@ -20,11 +22,93 @@ import { Button, Segmented, SelectRow } from '../components/ui.jsx' // Which muscles the training in a window actually hit — and, the point of the card, // which ones it keeps missing. Shading is relative within the window (lib/muscles.js). +function latestMuscleTraining(workouts) { + const latest = {} + for (const workout of workouts || []) { + const timestamp = Number(workout?.start || new Date(workout?.d).getTime()) + if (!Number.isFinite(timestamp)) continue + for (const entry of workout.entries || []) { + if (!(entry.sets || []).some(set => set?.done === true)) continue + for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) { + if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp + } + } + } + return latest +} + +const FATIGUE_LEVELS = [ + { at: 0, level: 4 }, + { at: 0.25, level: 2 }, + { at: 0.5, level: 0, exclusive: true }, +] + +const STRENGTH_LEVELS = [ + { at: STRENGTH_FLOOR, level: 0 }, + { at: 0.625, level: 1 }, + { at: 0.75, level: 2 }, + { at: 0.875, level: 3 }, + { at: 1, level: 4 }, +] + +function useNow() { + const [, setTick] = useState(0) + useEffect(() => { + const iv = setInterval(() => setTick(tick => tick + 1), 60000) + return () => clearInterval(iv) + }, []) + return Date.now() +} + +/** + * Return the whole weeks since a completed muscle-training timestamp. + * + * @param {number} now Current render-time timestamp in milliseconds. + * @param {number} lastTrained Timestamp of the latest completed training event. + * @returns {number} Non-negative whole weeks, including zero for ages under seven days. + */ +export function weeksSinceTraining(now, lastTrained) { + return Math.max(0, Math.floor((now - lastTrained) / 86400000 / 7)) +} + +function FatigueLegend() { + return
+ {t('Fatigued')}
+ {t('Recovering')}
+ {t('Ready')}
+
+} + +function StrengthLegend() { + return
+ 1
+
{fmtNum(STRENGTH_FLOOR)} +
+} + +function fatigueLabel(value) { + const state = fatigueStateOf(value) + return t(state === 'ready' ? 'Ready' : state === 'recovering' ? 'Recovering' : 'Fatigued') +} + function MuscleBalance({ S }) { + const [view, setView] = useState('balance') const [win, setWin] = useState(7) const [hard, setHard] = useState(false) const [sel, setSel] = useState(null) - const now = Date.now() + const now = useNow() + const workouts = S.workouts + const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now]) + const strength = useMemo(() => strengthOf(workouts, now), [workouts, now]) + const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts]) + const { worked: strengthOrder } = rankOf(strength) + const detrained = strengthOrder.filter(slug => strength[slug] < 1) + const strengthHint = slug => { + if (lastTrained[slug] == null) return t('not trained') + const weeks = weeksSinceTraining(now, lastTrained[slug]) + return t('Weeks since training: {0}', weeks) + } + const toggleSel = m => setSel(s => (s === m ? null : m)) const inWin = S.workouts.filter(w => win === 0 ? true : win === 7 ? weekKey(w.d) === weekKey(todayISO()) @@ -42,35 +126,58 @@ function MuscleBalance({ S }) { const sets = m => Math.round((load[m] || 0) * 10) / 10 return
-
-

{t('Muscle balance')} · {on ? t('by hard sets') : t('by sets worked')}

- {rated && } -
- { setWin(v); setSel(null) }} - options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} /> - {inWin.length ? <> - setSel(s => (s === m ? null : m))} /> - + + {view === 'balance' ? <> +
+

{t('Muscle balance')} · {on ? t('by hard sets') : t('by sets worked')}

+ {rated && } +
+ { setWin(v); setSel(null) }} + options={[{ value: 7, label: t('Week') }, { value: 30, label: '30d' }, { value: 90, label: '90d' }, { value: 0, label: t('All') }]} /> + {inWin.length ? <> + setSel(s => (s === m ? null : m))} /> + + {sel &&
+ {t(MUSCLE_NAME[sel])} + {sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')} +
} + {!sel && top.map(m =>
+ {t(MUSCLE_NAME[m])} + + {t('{0} sets', sets(m))} +
)} + {missed.length > 0 && <> +

{on ? t('No hard sets in this period') : t('Not trained in this period')}

+
{missed.map(m => {t(MUSCLE_NAME[m])})}
+ } + {!missed.length && worked.length > 0 && +
{on + ? t('Every muscle group got at least one hard set in this period.') + : t('Every muscle group got some work in this period.')}
} + :
{t('No workouts in this period yet.')}
} + : view === 'fatigue' ? <> +

{t('Fatigue')}

+ + +
{t('Fatigue shows how recently each muscle was trained. High means rest.')}
{sel &&
{t(MUSCLE_NAME[sel])} - {sets(sel) ? t('{0} sets', sets(sel)) : on ? t('no hard sets') : t('not trained')} + {fatigueLabel(fatigue[sel])}
} - {!sel && top.map(m =>
- {t(MUSCLE_NAME[m])} - - {t('{0} sets', sets(m))} + : <> +

{t('Strength')}

+ + +
{t('Strength shows retained muscle strength. Train again to reset it.')}
+ {detrained.map(slug =>
+ {t(MUSCLE_NAME[slug])} + + {strengthHint(slug)}
)} - {missed.length > 0 && <> -

{on ? t('No hard sets in this period') : t('Not trained in this period')}

-
{missed.map(m => {t(MUSCLE_NAME[m])})}
- } - {!missed.length && worked.length > 0 && -
{on - ? t('Every muscle group got at least one hard set in this period.') - : t('Every muscle group got some work in this period.')}
} - :
{t('No workouts in this period yet.')}
} + }
} diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx new file mode 100644 index 0000000..e21db45 --- /dev/null +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -0,0 +1,300 @@ +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { parseHTML } from 'linkedom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js' +import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js' +import { fatigueStateOf } from '../lib/recovery-view.js' +import Stats, { weeksSinceTraining } from './Stats.jsx' + +const DAY = 86400000 +const HOUR = 3600000 +const BASE_NOW = Date.UTC(2026, 0, 22, 12) + +const mocks = vi.hoisted(() => ({ + maps: [], + mapMounts: 0, + S: { + unit: 'kg', body: 'male', effort: 'rir', targetW: null, + bodyweight: [], routines: [], workouts: [], + }, +})) + +vi.mock('../store/useStore.js', () => ({ + useStore: selector => selector({ S: mocks.S }), +})) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {}, + WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit', +})) +vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') })) +vi.mock('../components/Heatmap.jsx', () => ({ default: () => React.createElement('div') })) +vi.mock('../components/Icon.jsx', () => ({ default: props => React.createElement('span', props) })) +vi.mock('../components/BodyMap.jsx', () => ({ + default: props => { + mocks.maps.push(props) + React.useEffect(() => { + mocks.mapMounts++ + return () => {} + }, []) + return React.createElement( + 'div', + { 'data-body-map': true, 'data-selected-muscle': props.selected || '' }, + React.createElement('button', { + 'data-muscle': 'chest', + onClick: () => props.onMuscle?.('chest'), + }, 'Chest'), + ) + }, + BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }), +})) + +let dom +let root +let container + +function iso(timestamp) { + return new Date(timestamp).toISOString().slice(0, 10) +} + +function set(done, extra = {}) { + return { done, w: 10, r: 8, ...extra } +} + +function workout(id, start, entries) { + return { id, d: iso(start), start, entries } +} + +function entry(id, sets) { + return { id, sets } +} + +function lifecycleWorkouts(now = BASE_NOW) { + // The 36-hour fatigue edge crosses .5 after one 60-second interval tick. + const fatigueEdge = now - (36 * HOUR - 30000) + // This completed set is in the initial 30-day Balance window, then ages out after one tick. + const balanceEdge = now - (30 * DAY - 30000) + // The 14-day strength edge becomes sub-full after one tick. + const strengthEdge = now - (14 * DAY - 30000) + // This completed event must remain the latest training event for abs: the newer set is undone. + const absCompleted = now - 20 * DAY + const absUndone = now - DAY + return [ + workout('fatigue-edge', fatigueEdge, [entry('1254', [set(true, { rir: 0 })])]), + workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]), + workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]), + workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]), + workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]), + ] +} + +function allFatiguedWorkout(now = BASE_NOW) { + // Primary muscles have one completed set. The three secondary-only map slugs have two + // completed sets so their .4 weights are also above the production .5 fatigue boundary. + const ids = [ + ['1018', 1], // trapezius + ['1012', 1], // deltoids + ['1167', 1], // chest + ['1013', 1], // upper-back + ['3011', 1], // serratus + ['1413', 1], // biceps + ['1399', 1], // triceps + ['1016', 1], // forearm + ['1005', 2], // abs + obliques + ['1010', 1], // lower-back + ['1003', 1], // gluteal + ['1001', 1], // quadriceps + ['1511', 1], // hamstring + ['1494', 1], // adductors + ['1002', 2], // abs + hip-flexors + ['1000', 1], // calves + ['1396', 2], // calves + tibialis + ] + return workout('all-fatigued', now, ids.map(([id, count]) => entry(id, Array.from({ length: count }, () => set(true))))) +} + +function allSubfullWorkout(now = BASE_NOW) { + return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])]) +} + +function resetFixture(workouts = lifecycleWorkouts()) { + mocks.S.workouts = workouts + mocks.maps.length = 0 + mocks.mapMounts = 0 +} + +function installDom() { + const parsed = parseHTML('
') + dom = parsed.window + globalThis.window = dom + globalThis.document = dom.document + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator }) + for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key] + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.getElementById('root') + root = createRoot(container) +} + +async function mountStats() { + installDom() + await act(async () => { root.render(React.createElement(Stats)) }) +} + +async function unmountStats() { + if (!root) return + await act(async () => { root.unmount() }) + root = null + container = null + dom = null +} + +function muscleCard() { + return [...container.querySelectorAll('.card')].find(card => + [...card.querySelectorAll('.seg button')].some(button => + ['Muscle balance', 'Fatigue', 'Strength'].includes(button.textContent.trim()))) +} + +function buttonWithText(scope, text) { + return [...scope.querySelectorAll('button')].find(button => button.textContent.trim() === text) +} + +function viewButton(text) { + return buttonWithText(muscleCard(), text) +} + +function balanceRangeButton(text) { + const segments = muscleCard().querySelectorAll('.seg') + return buttonWithText(segments[1], text) +} + +async function click(button) { + expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy() + await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) +} + +async function tick(milliseconds) { + await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) }) +} + +function lastMap() { + return mocks.maps.at(-1) +} + +function expectPressed(button) { + expect(button?.getAttribute('aria-pressed')).toBe('true') +} + +function strengthRows() { + return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim()) +} + +afterEach(async () => { + await unmountStats() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(BASE_NOW) + resetFixture() +}) + +describe('Stats muscle recovery view runtime', () => { + it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => { + await mountStats() + const card = muscleCard() + + expectPressed(buttonWithText(card, 'Muscle balance')) + expectPressed(buttonWithText(card, 'Week')) + + await click(balanceRangeButton('30d')) + await click(buttonWithText(card, 'All')) + await click(card.querySelector('[data-muscle="chest"]')) + expectPressed(balanceRangeButton('30d')) + expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() + expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() + + await click(viewButton('Fatigue')) + expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.') + await click(viewButton('Strength')) + expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.') + await click(viewButton('Muscle balance')) + + expectPressed(balanceRangeButton('30d')) + expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() + expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() + expect(lastMap().selected).toBe('chest') + expect(lastMap().load.chest).toBe(2) + }) + + it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => { + await mountStats() + await click(balanceRangeButton('30d')) + await click(viewButton('Fatigue')) + await click(muscleCard().querySelector('[data-muscle="chest"]')) + + const beforeTickMounts = mocks.mapMounts + const beforeTick = lastMap().load.chest + expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED) + expect(container.textContent).toContain('Fatigued') + + await tick(60000) + + const afterTick = lastMap().load.chest + expect(mocks.mapMounts).toBe(beforeTickMounts) + expect(afterTick).toBeLessThan(0.5) + expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING) + expect(container.textContent).toContain('Recovering') + + await click(viewButton('Strength')) + expect(lastMap().load.quadriceps).toBeLessThan(1) + expect(strengthRows()).toContain('Quads') + + await click(viewButton('Muscle balance')) + expect(lastMap().load.chest).toBe(1) + expectPressed(balanceRangeButton('30d')) + }) + + it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => { + await mountStats() + await click(viewButton('Strength')) + + const load = lastMap().load + const expectedRows = rankOf(load).worked + .filter(slug => load[slug] < 1) + .map(slug => MUSCLE_NAME[slug]) + expect(strengthRows()).toEqual(expectedRows) + + // The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago. + expect(container.textContent).toContain('Weeks since training: 2') + + // The production helper used by Stats' rendered strength hint floors six elapsed days to zero. + expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0) + }) + + it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => { + expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY) + expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING) + expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING) + expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED) + + resetFixture([allFatiguedWorkout()]) + await mountStats() + await click(viewButton('Fatigue')) + const fatigueMap = lastMap() + expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES) + expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true) + expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 0)).toBe(true) + + await unmountStats() + resetFixture([allSubfullWorkout()]) + await mountStats() + await click(viewButton('Strength')) + const strengthMap = lastMap() + expect(Object.values(strengthMap.load).every(value => value < 1)).toBe(true) + expect(Math.min(...Object.values(strengthMap.load))).toBe(STRENGTH_FLOOR) + expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 }) + }) +}) From 9af028bde349ec3cdc93d5d09784b34b95791cd3 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:16:08 +0200 Subject: [PATCH 11/58] confirmed UI tweaks: fatigued highlighted (red/amber), strongest gold, strength scale labels, exercise list by current strength, 90d volume on strength rows --- frontend/src/index.css | 12 ++++++ frontend/src/locales/de.js | 2 + frontend/src/locales/es.js | 2 + frontend/src/locales/fr.js | 2 + frontend/src/locales/hi.js | 2 + frontend/src/locales/it.js | 2 + frontend/src/locales/ko.js | 2 + frontend/src/locales/pl.js | 2 + frontend/src/locales/pt.js | 2 + frontend/src/locales/ru.js | 2 + frontend/src/locales/tr.js | 2 + frontend/src/locales/zh.js | 2 + frontend/src/views/Stats.jsx | 43 +++++++++++++++------- frontend/src/views/Stats.recovery.test.jsx | 10 ++--- 14 files changed, 69 insertions(+), 18 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index 9de4f63..024eebe 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -777,6 +777,18 @@ h4.sec{ .bm-m.l2{fill:color-mix(in srgb,var(--acc) 56%,var(--bm-base))} .bm-m.l3{fill:color-mix(in srgb,var(--acc) 78%,var(--bm-base))} .bm-m.l4{fill:var(--acc)} +/* Fatigue view: attention ramp - fatigued muscles highlighted (owner tweak 2026-08-06) */ +.hm-fatigue .bm-m.l4{fill:var(--red)} +.hm-fatigue .bm-m.l3{fill:var(--orange)} +.hm-fatigue .bm-m.l2{fill:var(--yellow)} +.hm-fatigue .bm-m.l1{fill:color-mix(in srgb,var(--yellow) 32%,var(--bm-base))} +.hm-fatigue .hm-c.l4{background:var(--red)} +.hm-fatigue .hm-c.l3{background:var(--orange)} +.hm-fatigue .hm-c.l2{background:var(--yellow)} +/* Strength view: top band pops gold (owner tweak 2026-08-06) */ +.hm-strength .bm-m.l4{fill:var(--yellow);filter:drop-shadow(0 0 1.5px var(--yellow))} +.hm-strength .hm-c.l4{background:var(--yellow)} + .bm-m.sel{stroke:var(--label);stroke-width:7} .bodymap.tappable .bm-m{cursor:pointer} /* A hairline in the surface colour separates neighbouring muscles; the artwork has no diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 2ad8876..69c5006 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -384,6 +384,8 @@ export default { 'Fatigued': 'Ermüdet', 'Fatigue shows how recently each muscle was trained. High means rest.': 'Die Ermüdung zeigt, wie lange das Training jedes Muskels zurückliegt. Ein hoher Wert bedeutet: Pause.', 'Strength shows retained muscle strength. Train again to reset it.': 'Die Kraft zeigt, wie viel Muskelkraft erhalten ist. Trainiere erneut, um sie zurückzusetzen.', + 'full': 'voll', + 'floor': 'Minimum', 'Weeks since training: {0}': 'Zuletzt vor {0} Wo. trainiert', 'by sets worked': 'nach Sätzen', 'Week': 'Woche', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 537af83..21bdad4 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Fatigado', 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatiga indica cuánto tiempo ha pasado desde el último entrenamiento de cada músculo. Un valor alto indica que toca descansar.', 'Strength shows retained muscle strength. Train again to reset it.': 'La fuerza muestra cuánta fuerza muscular se conserva. Vuelve a entrenar para restablecerla.', + 'full': 'completo', + 'floor': 'mínimo', 'Weeks since training: {0}': 'Último entrenamiento: hace {0} sem.', 'by sets worked': 'por series trabajadas', 'Week': 'Semana', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index e233a3b..df946a2 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Fatigué', 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatigue indique à quand remonte le dernier entraînement de chaque muscle. Un niveau élevé signifie qu’il est temps de se reposer.', 'Strength shows retained muscle strength. Train again to reset it.': 'La force indique combien de force musculaire est conservée. Entraîne-toi à nouveau pour la réinitialiser.', + 'full': 'complet', + 'floor': 'plancher', 'Weeks since training: {0}': 'Dernier entraînement : il y a {0} sem.', 'by sets worked': 'par séries effectuées', 'Week': 'Semaine', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index bbf2947..e649b62 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'थकी हुई', 'Fatigue shows how recently each muscle was trained. High means rest.': 'थकान बताती है कि हर मांसपेशी की ट्रेनिंग कितनी हाल की है। अधिक थकान होने पर आराम करें।', 'Strength shows retained muscle strength. Train again to reset it.': 'शक्ति बताती है कि मांसपेशियों की कितनी ताकत बनी हुई है। इसे रीसेट करने के लिए फिर से ट्रेन करें।', + 'full': 'पूर्ण', + 'floor': 'न्यूनतम', 'Weeks since training: {0}': 'पिछला व्यायाम: {0} सप्ताह पहले', 'by sets worked': 'सेट के अनुसार', 'Week': 'सप्ताह', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 5ccc24b..dc4795e 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Affaticato', 'Fatigue shows how recently each muscle was trained. High means rest.': 'La fatica mostra quanto è recente l’allenamento di ogni muscolo. Un valore alto significa che serve riposo.', 'Strength shows retained muscle strength. Train again to reset it.': 'La forza mostra quanta forza muscolare hai mantenuto. Allenati di nuovo per reimpostarla.', + 'full': 'pieno', + 'floor': 'minimo', 'Weeks since training: {0}': 'Ultimo allenamento: {0} sett. fa', 'by sets worked': 'per serie svolte', 'Week': 'Settimana', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 1bcc2bd..a09a4ce 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -366,6 +366,8 @@ export default { 'Fatigued': '피로함', 'Fatigue shows how recently each muscle was trained. High means rest.': '피로도는 각 근육을 얼마나 최근에 운동했는지 보여줍니다. 높을수록 휴식이 필요합니다.', 'Strength shows retained muscle strength. Train again to reset it.': '근력은 근육에 남아 있는 힘을 보여줍니다. 다시 운동하면 값이 초기화됩니다.', + 'full': '완전', + 'floor': '최소', 'Weeks since training: {0}': '마지막 운동: {0}주 전', 'by sets worked': '세트 수 기준', 'Week': '이번 주', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index dae273c..2f59aa5 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Zmęczony', 'Fatigue shows how recently each muscle was trained. High means rest.': 'Zmęczenie pokazuje, jak niedawno trenowano każdą partię mięśni. Wysoki poziom oznacza potrzebę odpoczynku.', 'Strength shows retained muscle strength. Train again to reset it.': 'Siła pokazuje, ile siły mięśniowej pozostało. Ponowny trening przywraca jej poziom wyjściowy.', + 'full': 'pełna', + 'floor': 'minimum', 'Weeks since training: {0}': 'Trening: {0} tyg. temu', 'by sets worked': 'wg serii', 'Week': 'Tydzień', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index a181fe3..578cd86 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Fatigado', 'Fatigue shows how recently each muscle was trained. High means rest.': 'A fadiga mostra há quanto tempo cada músculo foi treinado. Um nível elevado significa que é preciso descansar.', 'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanta força muscular se mantém. Treina novamente para repor o valor.', + 'full': 'completo', + 'floor': 'mínimo', 'Weeks since training: {0}': 'Treino: há {0} sem.', 'by sets worked': 'por séries trabalhadas', 'Week': 'Semana', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index a3ba4a7..a1882b6 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Утомлена', 'Fatigue shows how recently each muscle was trained. High means rest.': 'Усталость показывает, насколько недавно тренировалась каждая мышца. Высокий уровень означает, что пора отдохнуть.', 'Strength shows retained muscle strength. Train again to reset it.': 'Сила показывает, сколько мышечной силы сохранилось. Повторная тренировка сбрасывает это значение.', + 'full': 'полная', + 'floor': 'минимум', 'Weeks since training: {0}': 'Тренировка: {0} нед. назад', 'by sets worked': 'по подходам', 'Week': 'Неделя', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 60c3760..87fe222 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -366,6 +366,8 @@ export default { 'Fatigued': 'Yorgun', 'Fatigue shows how recently each muscle was trained. High means rest.': 'Yorgunluk, her kasın ne kadar süre önce çalıştırıldığını gösterir. Yüksek değer dinlenmek gerektiği anlamına gelir.', 'Strength shows retained muscle strength. Train again to reset it.': 'Kuvvet, kas gücünün ne kadarının korunduğunu gösterir. Yeniden çalışarak değeri sıfırlayabilirsin.', + 'full': 'tam', + 'floor': 'minimum', 'Weeks since training: {0}': 'Son antrenman: {0} hafta önce', 'by sets worked': 'çalışılan sete göre', 'Week': 'Hafta', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index bf33ba5..68d1134 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -366,6 +366,8 @@ export default { 'Fatigued': '已疲劳', 'Fatigue shows how recently each muscle was trained. High means rest.': '疲劳度显示每个肌群最近一次训练距今多久。数值越高,越需要休息。', 'Strength shows retained muscle strength. Train again to reset it.': '力量显示肌肉力量保留了多少。再次训练即可重置。', + 'full': '完全', + 'floor': '下限', 'Weeks since training: {0}': '上次训练:{0}周前', 'by sets worked': '按训练组数', 'Week': '本周', diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 9da7f0f..febef34 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -38,9 +38,9 @@ function latestMuscleTraining(workouts) { } const FATIGUE_LEVELS = [ - { at: 0, level: 4 }, + { at: 0, level: 0 }, { at: 0.25, level: 2 }, - { at: 0.5, level: 0, exclusive: true }, + { at: 0.5, level: 4, exclusive: true }, ] const STRENGTH_LEVELS = [ @@ -72,17 +72,17 @@ export function weeksSinceTraining(now, lastTrained) { } function FatigueLegend() { - return
- {t('Fatigued')}
+ return
+ {t('Fatigued')}
{t('Recovering')}
- {t('Ready')}
+ {t('Ready')}
} function StrengthLegend() { - return
- 1
-
{fmtNum(STRENGTH_FLOOR)} + return
+ 1 {t('full')}
+
{fmtNum(STRENGTH_FLOOR)} {t('floor')}
} @@ -120,6 +120,8 @@ function MuscleBalance({ S }) { const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s)))) const on = hard && rated const load = loadOfWorkouts(inWin, on ? isHardSet : null) + const volWin = S.workouts.filter(w => historyUnitCompatible(w, S.unit) && (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) + const vol90 = loadOfWorkouts(volWin, null) const { worked, missed } = rankOf(load) const top = worked.slice(0, 4) const max = worked.length ? load[worked[0]] : 0 @@ -160,7 +162,7 @@ function MuscleBalance({ S }) { :
{t('No workouts in this period yet.')}
} : view === 'fatigue' ? <>

{t('Fatigue')}

- +
{t('Fatigue shows how recently each muscle was trained. High means rest.')}
{sel &&
@@ -169,13 +171,13 @@ function MuscleBalance({ S }) {
} : <>

{t('Strength')}

- +
{t('Strength shows retained muscle strength. Train again to reset it.')}
{detrained.map(slug =>
{t(MUSCLE_NAME[slug])} - {strengthHint(slug)} + {t('{0} sets', vol90[slug] || 0)}
)} }
@@ -254,7 +256,21 @@ export default function Stats() { const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length - const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]).sort((a, b) => EXIDX[a].n < EXIDX[b].n ? -1 : 1) + const currentOf = id => { + for (let i = S.workouts.length - 1; i >= 0; i--) { + const en = S.workouts[i].entries.find(e => e.id === id) + if (!en) continue + const mode = modeOf({ ...(en.target || {}), id }) + const metric = s2 => mode === 'cardio' ? (s2.speed || 0) : mode === 'time' ? (s2.sec || 0) : (s2.w || 0) + const mx = Math.max(0, ...en.sets.filter(s2 => s2.done).map(metric), mode === 'time' || mode === 'cardio' ? 0 : (en.topW || 0)) + if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit } + } + return { mx: 0, unit: S.unit } + } + const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]) + const exCurrent = Object.fromEntries(exHist.map(id => [id, currentOf(id)])) + exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || (EXIDX[a].n < EXIDX[b].n ? -1 : 1)) + const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null // How this exercise was logged most recently decides what the curve means: top weight, // longest hold or top speed. Sets logged in another mode lack the field and score 0, so a @@ -339,7 +355,8 @@ export default function Stats() { {exHist.length ? <>
({ value: id, label: EXIDX[id].n }))} /> + options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' — ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /> +
{exOpts.length > 1 && }
diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index e21db45..6bfc209 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -59,11 +59,11 @@ function iso(timestamp) { } function set(done, extra = {}) { - return { done, w: 10, r: 8, ...extra } + return { done, w: 10, r: 8, unit: 'kg', ...extra } } function workout(id, start, entries) { - return { id, d: iso(start), start, entries } + return { id, d: iso(start), start, unit: 'kg', entries } } function entry(id, sets) { @@ -204,7 +204,7 @@ beforeEach(() => { describe('Stats muscle recovery view runtime', () => { it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => { await mountStats() - const card = muscleCard() + const card = muscleCard() expectPressed(buttonWithText(card, 'Muscle balance')) expectPressed(buttonWithText(card, 'Week')) @@ -268,7 +268,7 @@ describe('Stats muscle recovery view runtime', () => { expect(strengthRows()).toEqual(expectedRows) // The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago. - expect(container.textContent).toContain('Weeks since training: 2') + expect(container.textContent).toContain('1 sets') // The production helper used by Stats' rendered strength hint floors six elapsed days to zero. expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0) @@ -286,7 +286,7 @@ describe('Stats muscle recovery view runtime', () => { const fatigueMap = lastMap() expect(Object.keys(fatigueMap.load)).toEqual(MUSCLES) expect(Object.values(fatigueMap.load).every(value => value > 0.5)).toBe(true) - expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 0)).toBe(true) + expect(Object.values(levelsOf(fatigueMap.load, fatigueMap.thresholds)).every(level => level === 4)).toBe(true) await unmountStats() resetFixture([allSubfullWorkout()]) From d1cede21d3f95b38052c3f3ec36e13434f6ae52c Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:16:47 +0200 Subject: [PATCH 12/58] fix dropdown label em-dash expression --- frontend/src/views/Stats.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index febef34..41be0e7 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -355,7 +355,7 @@ export default function Stats() { {exHist.length ? <>
({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' — ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /> + options={exHist.map(id => ({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
{exOpts.length > 1 && } From 6c91adefcd28e8328ba2eb0df4bf81556b8ea9e3 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:17:41 +0200 Subject: [PATCH 13/58] volWin: plain 90d window filter (upstream-adapted) --- frontend/src/views/Stats.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 41be0e7..3186f9c 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -120,7 +120,7 @@ function MuscleBalance({ S }) { const rated = inWin.some(w => w.entries.some(e => e.sets.some(s => s.done && isHardSet(s)))) const on = hard && rated const load = loadOfWorkouts(inWin, on ? isHardSet : null) - const volWin = S.workouts.filter(w => historyUnitCompatible(w, S.unit) && (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) + const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) const vol90 = loadOfWorkouts(volWin, null) const { worked, missed } = rankOf(load) const top = worked.slice(0, 4) From 5b5d65b63e451ce44762a7f2bdac7fdcaaf148d3 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:39:59 +0200 Subject: [PATCH 14/58] Add local notification on rest timer completion --- frontend/src/store/useUI.js | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js index b4eb439..0330ee7 100644 --- a/frontend/src/store/useUI.js +++ b/frontend/src/store/useUI.js @@ -10,6 +10,35 @@ import { useStore } from './useStore.js' const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) } const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) } +const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window +let requestRestNotificationPermissionP = null + +const requestRestNotificationPermission = async () => { + if (!notificationsSupported()) return false + if (Notification.permission === 'granted') return true + if (Notification.permission === 'denied') return false + if (!requestRestNotificationPermissionP) { + requestRestNotificationPermissionP = Notification.requestPermission() + .then(perm => perm === 'granted') + .catch(() => false) + .finally(() => { + requestRestNotificationPermissionP = null + }) + } + return requestRestNotificationPermissionP +} + +const maybeRestNotification = async () => { + if (!notificationsSupported()) return + if (!document.hidden && document.visibilityState !== 'hidden') return + if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return + try { + new Notification(t('Rest over'), { body: t('Rest over — next set!') }) + } catch { + // Intentionally ignore: notification APIs vary by browser and policy in edge cases. + } +} + let toastTm = null let timerInt = null let timerTick = null @@ -42,6 +71,7 @@ export const useUI = create((set, get) => ({ get().stopRest() const endsAt = Date.now() + sec * 1000 set({ timer: { left: sec, total: sec, endsAt } }) + requestRestNotificationPermission() pushRestTimer(sec) timerTick = () => { const tm = get().timer @@ -51,7 +81,7 @@ export const useUI = create((set, get) => ({ const snd = useStore.getState().S.sound if (left <= 0) { beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5) - vibrate([200, 100, 200]); get().toast(t('Rest over — next set!')); get().stopRest(); return + vibrate([200, 100, 200]); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return } if (left <= 3) beep(snd, 660, 0.1) set({ timer: { ...tm, left } }) From 941d911fa9ac0eb1eb89c1b9da6959b4131310f1 Mon Sep 17 00:00:00 2001 From: Space_Hermes Date: Thu, 6 Aug 2026 19:46:18 +0200 Subject: [PATCH 15/58] feat: enrich common row muscle metadata --- frontend/src/lib/exercises.js | 17 +++++++++++++++- frontend/src/lib/muscles.test.js | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 frontend/src/lib/muscles.test.js diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index 0bd6552..7f6adf4 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -2,8 +2,23 @@ import { EXDB } from './exercises-data.js' import { t } from './i18n-core.js' export { EXDB } + +// The generated dataset already supplies secondary muscles for most exercises. Keep the +// handful of conservative catalogue additions that are useful to the muscle map here so a +// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary. +const SECONDARY_ADDITIONS = { + '0027': ['rear deltoids'], // barbell bent over row + '0293': ['rear deltoids'], // dumbbell bent over row + '0499': ['rear deltoids'], // inverted row + '0861': ['rear deltoids'], // cable seated row +} + export const EXIDX = {} -EXDB.forEach(e => { EXIDX[e.id] = e }) +EXDB.forEach(e => { + const additions = SECONDARY_ADDITIONS[e.id] + if (additions) e.sm = [...new Set([...(e.sm || []), ...additions])] + EXIDX[e.id] = e +}) export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort() // Equipment options present in a given list of exercises, most common first (issue #6). diff --git a/frontend/src/lib/muscles.test.js b/frontend/src/lib/muscles.test.js new file mode 100644 index 0000000..6d45dd5 --- /dev/null +++ b/frontend/src/lib/muscles.test.js @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { EXIDX } from './exercises.js' +import { musclesOf } from './muscles.js' + +// The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps +// those aliases to the canonical body-map slugs and applies the 0.4 support weight. +describe('catalogue secondary muscles', () => { + it('maps a bench press to chest, triceps and deltoids', () => { + expect(musclesOf(EXIDX['0025'])).toMatchObject({ + chest: 1, + triceps: 0.4, + deltoids: 0.4, + }) + }) + + it('maps a squat to glutes, quads and hamstrings', () => { + expect(musclesOf(EXIDX['0043'])).toMatchObject({ + gluteal: 1, + quadriceps: 0.4, + hamstring: 0.4, + }) + }) + + it('maps common row variations to the upper back, biceps and rear deltoids', () => { + for (const id of ['0027', '0293', '0499', '0861']) { + expect(musclesOf(EXIDX[id])).toMatchObject({ + 'upper-back': 1, + biceps: 0.4, + deltoids: 0.4, + }) + } + }) +}) From 84e98425ccaa7f616a4b3bb7eeabb3281c05317e Mon Sep 17 00:00:00 2001 From: Space-Hermes Date: Thu, 6 Aug 2026 19:54:36 +0200 Subject: [PATCH 16/58] feat: prefill freestyle exercises from last workout --- frontend/src/lib/history.js | 22 ++++++++- frontend/src/lib/history.test.js | 84 +++++++++++++++++++++++++++++++- frontend/src/sheets.jsx | 6 +-- frontend/src/views/Workout.jsx | 22 ++++++--- 4 files changed, 121 insertions(+), 13 deletions(-) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index 2fe59d0b..71a1fa8 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -152,6 +152,21 @@ export function lastEntryFor(S, exId) { } return null } + +// A freestyle exercise starts with the last target the user actually trained, rather than the +// generic config sheet defaults used when there is no history. The set rows themselves are still +// built by buildSets(), which copies each completed set by position; only the target shape and +// number of rows need to be seeded here so the config sheet and the rows agree. +export function freestyleConfig(S, cfg) { + const last = lastEntryFor(S, cfg.id) + if (!last) return { ...cfg } + return { + ...cfg, + ...(last.target || {}), + id: cfg.id, + sets: Math.max(1, last.sets.length) + } +} export function bestWeightFor(S, exId) { let best = 0 S.workouts.forEach(w => w.entries.forEach(e => { @@ -173,10 +188,11 @@ export function effectiveRoutine(S, iso) { const id = effectiveRoutineId(S, iso) return id ? S.routines.find(r => r.id === id) || null : null } -export function buildSets(S, cfg) { +export function buildSets(S, cfg, options = {}) { const last = lastEntryFor(S, cfg.id) const n = Math.max(1, cfg.sets || 1) const mode = modeOf(cfg) + const preferLast = !!options.preferLast const sets = [] // Last time's set at the same position, falling back to its final set when the plan grew. const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null) @@ -202,7 +218,9 @@ export function buildSets(S, cfg) { for (let i = 0; i < n; i++) { const prev = prevAt(i) const usable = prev && prev.r > 0 ? prev : null - const w = conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight) + // Planned sessions may use the confirmed working weight, while freestyle should reproduce + // the load of each matching set when that option is requested. + const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight)) sets.push({ w, r: usable ? usable.r : cfg.reps, done: false }) } return sets diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 0117e22..1b8a3d2 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js' +import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -336,6 +336,80 @@ describe('exLine', () => { const emptyS = { workouts: [], exWeights: {} } +describe('freestyleConfig', () => { + it('inherits the last target and completed set count for a newly added exercise', () => { + const S = { + exWeights: {}, + workouts: [{ + d: '2026-01-01', + entries: [{ + id: LIFT, + target: { mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' }, + sets: [ + { w: 60, r: 8, done: true }, + { w: 62.5, r: 7, done: true }, + { w: 62.5, r: 6, done: true }, + { w: 62.5, r: 5, done: true } + ] + }] + }] + } + const cfg = freestyleConfig(S, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 0 }) + + expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 4, reps: 8, weight: 60, prog: 'linear' }) + expect(buildSets(S, cfg)).toEqual([ + { w: 60, r: 8, done: false }, + { w: 62.5, r: 7, done: false }, + { w: 62.5, r: 6, done: false }, + { w: 62.5, r: 5, done: false } + ]) + }) + + it('inherits the target for timed and cardio exercises too', () => { + const timed = { + exWeights: {}, + workouts: [{ + d: '2026-01-02', + entries: [{ + id: LIFT, + target: { mode: 'time', sets: 2, sec: 60, weight: 15 }, + sets: [{ sec: 55, w: 15, done: true }, { sec: 60, w: 17.5, done: true }] + }] + }] + } + const cardio = { + exWeights: {}, + workouts: [{ + d: '2026-01-03', + entries: [{ + id: CARDIO, + target: { sets: 2, min: 30, speed: 7 }, + sets: [{ min: 28, speed: 7, done: true }, { min: 30, speed: 7.5, done: true }] + }] + }] + } + + const timedCfg = freestyleConfig(timed, { id: LIFT, mode: 'time', sets: 3, sec: 45, weight: 0 }) + expect(timedCfg).toEqual({ id: LIFT, mode: 'time', sets: 2, sec: 60, weight: 15 }) + expect(buildSets(timed, timedCfg)).toEqual([ + { sec: 55, w: 15, done: false }, + { sec: 60, w: 17.5, done: false } + ]) + + const cardioCfg = freestyleConfig(cardio, { id: CARDIO, sets: 1, min: 20, speed: 8 }) + expect(cardioCfg).toEqual({ id: CARDIO, sets: 2, min: 30, speed: 7 }) + expect(buildSets(cardio, cardioCfg)).toEqual([ + { min: 28, speed: 7, done: false }, + { min: 30, speed: 7.5, done: false } + ]) + }) + + it('keeps the supplied defaults when there is no completed matching workout', () => { + const cfg = freestyleConfig(emptyS, { id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 }) + expect(cfg).toEqual({ id: LIFT, mode: 'reps', sets: 3, reps: 10, weight: 50 }) + }) +}) + describe('buildSets', () => { it('builds reps sets from the plan when there is no history', () => { expect(buildSets(emptyS, { id: LIFT, sets: 3, reps: 8, weight: 50 })) @@ -374,6 +448,14 @@ describe('buildSets', () => { const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 10, done: true }] }] }] } expect(buildSets(S, { id: LIFT, sets: 1, reps: 8, weight: 50 })).toEqual([{ w: 75, r: 10, done: false }]) }) + + it('can preserve each last set weight for freestyle instead of using the working-weight hint', () => { + const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [ + { w: 60, r: 10, done: true }, { w: 62.5, r: 8, done: true } + ] }] }] } + expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true })) + .toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }]) + }) }) describe('workoutVolume', () => { diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 02dcb1b..39c8180 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -482,10 +482,10 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) { } -function ExConfig({ ex, existing, onSave, onDelete, close, routine }) { +function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) { const st = useStore(s => s.S) const cardio = isCardio(ex.id) - const [c, setC] = useState(existing || defaultConfig(ex.id)) + const [c, setC] = useState(existing || initial || defaultConfig(ex.id)) // Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for // everything else, which is where the gap was — planks, hangs, wall sits, loaded carries. const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id }) @@ -596,7 +596,7 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine }) { {onDelete && <>
} } -export const exConfigSheet = (ex, existing, onSave, onDelete, routine) => ui().openSheet(close => ) +export const exConfigSheet = (ex, existing, onSave, onDelete, routine, initial) => ui().openSheet(close => ) /* ============================ glyph picker ============================ */ // Grouped by what the glyph means for a training day, so picking one is a scan diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 3040bcc..c81d26c 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' -import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js' +import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js' import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' @@ -281,12 +281,20 @@ function ActiveWorkout() {
- +
{(() => { const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length From b2b35777448a09bbe860674e69a4e960485a48b7 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 7 Aug 2026 07:38:56 +0200 Subject: [PATCH 17/58] Release v1.2.6: Freestyle-Sessions starten dort, wo du aufgehoert hast --- CHANGELOG.md | 21 +++++++++++++++++++++ api/package.json | 2 +- frontend/package.json | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78539f1..d46674e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## v1.2.6 — 2026-08-07 + +A freestyle session no longer starts from blanks. Nothing else in the app changed. + +### Freestyle sessions start where you left off + +- 🏋️ **Adding an exercise to an empty workout now prefills it from the last time you trained + it** — the same number of sets, with each row's reps and weight carried across by position. + Cardio brings its duration and speed, a hold brings its seconds. Until now every row opened on + the config-sheet defaults, so the first thing a freestyle session asked of you was to retype + what you already did last week. +- **The config sheet agrees with the rows it is about to create.** It opens on the last target you + actually trained rather than the generic default, so the set count you confirm is the set count + you get. +- **Planned sessions are untouched.** A routine-driven workout still runs the progression logic and + still applies its prescription; only the freestyle path — which has no prescription to apply — + reads from history instead. + +Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in +[#50](https://github.com/DuarteSantos8/openGym/pull/50). + ## v1.2.5 — 2026-08-04 Nothing in the app itself changed. This release adds an optional side door: a small server that diff --git a/api/package.json b/api/package.json index ba14e46..55c1ed1 100644 --- a/api/package.json +++ b/api/package.json @@ -1,6 +1,6 @@ { "name": "gym-api", - "version": "1.2.5", + "version": "1.2.6", "private": true, "type": "module", "main": "server.js", diff --git a/frontend/package.json b/frontend/package.json index b8b70ca..983b390 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "opengym-frontend", "private": true, - "version": "1.2.5", + "version": "1.2.6", "type": "module", "scripts": { "dev": "vite", From 9daf637044ddf8667dbb8c171eed82e8cd2eefc6 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 7 Aug 2026 08:10:19 +0200 Subject: [PATCH 18/58] Gastmodus abschaltbar: ALLOW_GUEST=0 nimmt die Tuer ohne Konto raus (#42) --- .env.example | 8 ++++++++ CHANGELOG.md | 22 ++++++++++++++++++++- README.md | 1 + api/server.js | 7 ++++++- docs/SELF_HOSTING.md | 13 +++++++++++- frontend/src/lib/guest.js | 15 ++++++++++++++ frontend/src/lib/guest.test.js | 36 ++++++++++++++++++++++++++++++++++ frontend/src/locales/de.js | 1 + frontend/src/locales/es.js | 1 + frontend/src/locales/fr.js | 1 + frontend/src/locales/hi.js | 1 + frontend/src/locales/it.js | 1 + frontend/src/locales/ko.js | 1 + frontend/src/locales/pl.js | 1 + frontend/src/locales/pt.js | 1 + frontend/src/locales/ru.js | 1 + frontend/src/locales/tr.js | 1 + frontend/src/locales/zh.js | 1 + frontend/src/store/useStore.js | 17 ++++++++++++++++ frontend/src/views/Login.jsx | 24 ++++++++++++++++------- 20 files changed, 144 insertions(+), 10 deletions(-) create mode 100644 frontend/src/lib/guest.js create mode 100644 frontend/src/lib/guest.test.js diff --git a/.env.example b/.env.example index ac3773c..380e6a0 100644 --- a/.env.example +++ b/.env.example @@ -33,6 +33,14 @@ RP_NAME=openGym # generate the codes from the admin dashboard): # # INVITE_ONLY=1 +# +# Remove the "Continue without account" button, so a profile is the only way in. +# Guest mode keeps everything in the browser and never touches this server, but +# on an instance meant for a known set of people it is still the wrong front +# door. Anyone already inside as a guest is signed out on their next visit; the +# data they made stays in that browser. Defaults to on (guests allowed): +# +# ALLOW_GUEST=0 # ── Session length (optional) ────────────────────────────────────────────── # How long a sign-in lasts, in days. Default 90 — long enough that people who diff --git a/CHANGELOG.md b/CHANGELOG.md index d46674e..3a28816 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,27 @@ ## v1.2.6 — 2026-08-07 -A freestyle session no longer starts from blanks. Nothing else in the app changed. +A freestyle session no longer starts from blanks, and a self-hosted instance can finally insist +that everyone using it has an account. + +### An instance can require an account (#42) + +- 🔒 **`ALLOW_GUEST=0` removes the "Continue without account" button.** Guest mode keeps everything + in the browser and never touches the server — no account, no sync, nothing the admin dashboard + can see — so on an instance meant for a known set of people it was a door leading nowhere + useful, and until now there was no way to close it. +- **It also ends guest sessions that already exist.** Guests never authenticate, so there is no + request for the server to start refusing; the switch reaches someone already inside on their + next visit, when the app checks the config and returns them to the login screen. Their data is + not deleted — it stays in that browser, and moves into a real profile if they create one on the + same device. +- **A server it cannot reach is not a server that said no.** The button is only withdrawn on an + explicit `allow_guest: false`; a failed config request, or a server too old to send the flag at + all, leaves guest mode exactly as it was. An instance that is merely offline for a moment does + not lock out everyone who never made an account. +- **Default is on, so nothing changes for existing instances.** Set it alongside `INVITE_ONLY=1`: + invite-only governs who may *create a profile* and says nothing about the guest button, which + never creates one. ### Freestyle sessions start where you left off diff --git a/README.md b/README.md index cfff491..4da510b 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,7 @@ All via `.env` (see `.env.example`): | `RP_NAME` | Name shown in the passkey prompt | `openGym` | | `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* | | `INVITE_ONLY` | Require an invite code to create a profile | *(off)* | +| `ALLOW_GUEST` | Offer "Continue without account" — set `0` to require a profile | *(on)* | Push notification keys are generated on first run and saved to `./data/vapid.json` — nothing to set. diff --git a/api/server.js b/api/server.js index e2dce66..80af0e5 100644 --- a/api/server.js +++ b/api/server.js @@ -19,6 +19,11 @@ const RP_NAME = process.env.RP_NAME || 'openGym'; // code the admin generates. Both default off so a fresh self-hosted instance stays open. const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean); const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || ''); +// Guest mode ("Continue without account") keeps everything in the browser and never touches this +// server — but on an instance meant for a known set of people, an entrance nobody can walk back +// out of is still the wrong front door (#42). Default ON, so existing instances are unchanged; +// the polarity is inverted from INVITE_ONLY because the safe default here is the permissive one. +const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || ''); // 90 days keeps someone who trains a few times a week permanently signed in without a stolen // cookie staying good for a year. Overridable because a family instance and one on the open // internet don't want the same number. Only affects cookies minted from now on — the expiry is @@ -256,7 +261,7 @@ const routes = { 'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }), // Public config the login screen needs before anyone is signed in. - 'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY }), + 'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST }), 'GET /api/me': async (req, res) => { const user = readSession(req); diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md index da61930..d130cfe 100644 --- a/docs/SELF_HOSTING.md +++ b/docs/SELF_HOSTING.md @@ -90,11 +90,12 @@ Visit `https://gym.example.com`, create your profile, and add it to your home sc Anyone who can reach the URL can create their own profile — each gets isolated data. That's the default: open signup, no admin. -If you'd rather control who gets in, two optional settings in `.env` turn that around: +If you'd rather control who gets in, three optional settings in `.env` turn that around: ```bash ADMIN_UIDS=youruserid # comma-separated; these users get the admin dashboard INVITE_ONLY=1 # new profiles need an invite code +ALLOW_GUEST=0 # remove "Continue without account" ``` Register your own passkey profile first, then find your id in `./data/db.json` under `users[].id` @@ -104,6 +105,16 @@ out and locked out everywhere until you re-enable it), and — with `INVITE_ONLY revoking invite codes. Existing accounts keep working when you switch invite-only on. Admin access is gated by your passkey and enforced server-side, so it needs no separate login. +`INVITE_ONLY=1` and `ALLOW_GUEST=0` answer different questions and are usually set together. +Invite-only controls who may *create a profile*; it says nothing about the **Continue without +account** button, which never creates one. Guest mode keeps everything in that browser and never +talks to the server — there is no account, no sync and nothing for the admin dashboard to show — +so on an instance meant for a known set of people it is a door that leads nowhere useful. With +`ALLOW_GUEST=0` the button is gone, and anyone already using the app as a guest is returned to the +login screen on their next visit. Their data is not deleted: it stays in that browser and comes +back if you ever switch guests on again, or moves into a real profile if they create one on the +same device. + Prefer to keep the whole thing off the open internet? A VPN or an auth proxy (Authelia, Cloudflare Access…) in front still works, and composes with the above. diff --git a/frontend/src/lib/guest.js b/frontend/src/lib/guest.js new file mode 100644 index 0000000..17c309f --- /dev/null +++ b/frontend/src/lib/guest.js @@ -0,0 +1,15 @@ +/** + * Whether "Continue without account" may be offered, given the public config from /api/config. + * + * Guest mode is allowed unless the server has *positively* said otherwise. That asymmetry is the + * whole point: a config we could not fetch — offline, server restarting, request failed — is not + * the same answer as `allow_guest: false`, and treating it as one would lock people out of an + * instance whose admin never disabled anything. An instance that really did disable guests says + * so on the next successful boot, and the session is ended then (see useStore.boot). + * + * Older servers predate the flag and send no `allow_guest` at all; they mean "allowed". + * + * @param {{allow_guest?: boolean}|null|undefined} config Parsed /api/config body, or null. + * @returns {boolean} true when the guest entrance may be shown and used. + */ +export const guestAllowed = config => !(config && config.allow_guest === false) diff --git a/frontend/src/lib/guest.test.js b/frontend/src/lib/guest.test.js new file mode 100644 index 0000000..8e76ec9 --- /dev/null +++ b/frontend/src/lib/guest.test.js @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { guestAllowed } from './guest.js' + +// The flag is the easy half. The half worth pinning down is what happens when the server did not +// answer: a failed config fetch must not be read as "guests are disabled", or an instance that is +// merely unreachable locks out everyone who never made an account (#42). +describe('guestAllowed', () => { + it('allows guests when the server says so', () => { + expect(guestAllowed({ allow_guest: true })).toBe(true) + }) + + it('refuses guests only on an explicit false', () => { + expect(guestAllowed({ allow_guest: false })).toBe(false) + }) + + it('allows guests when the config could not be fetched', () => { + expect(guestAllowed(null)).toBe(true) + expect(guestAllowed(undefined)).toBe(true) + }) + + it('allows guests against a server too old to send the flag', () => { + expect(guestAllowed({ invite_only: true })).toBe(true) + }) + + // A missing key and a falsy-but-not-false value are different things. Only `false` — what the + // server actually serialises — closes the door; anything else stays open rather than guessing. + it('does not treat other falsy values as a refusal', () => { + for (const v of [0, '', null, undefined, NaN]) { + expect(guestAllowed({ allow_guest: v })).toBe(true) + } + }) + + it('treats the string "false" as the misconfiguration it is, not as a refusal', () => { + expect(guestAllowed({ allow_guest: 'false' })).toBe(true) + }) +}) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index d62b7c5d..3520ec0 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -236,6 +236,7 @@ export default { 'Sign in with passkey': 'Mit Passkey anmelden', 'Create new profile': 'Neues Profil erstellen', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Dieser Browser unterstützt keine Passkeys — du kannst openGym trotzdem lokal auf diesem Gerät nutzen.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Dieser Browser unterstützt keine Passkeys, und dieser Server verlangt ein Konto. Probier einen Browser oder ein Gerät mit Passkey-Unterstützung.', 'Continue without account': 'Ohne Konto fortfahren', 'Passkeys use {0} — no passwords.': 'Passkeys nutzen {0} — keine Passwörter.', 'Each profile keeps its own plan, workouts & body weight.': 'Jedes Profil hat seinen eigenen Plan, Trainings & Körpergewicht.', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 27c17f0..d2d06fb 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Iniciar sesión con passkey', 'Create new profile': 'Crear perfil nuevo', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador no admite passkeys — aun así puedes usar openGym localmente en este dispositivo.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador no admite passkeys y este servidor requiere una cuenta. Prueba con un navegador o dispositivo compatible con passkeys.', 'Continue without account': 'Continuar sin cuenta', 'Passkeys use {0} — no passwords.': 'Las passkeys usan {0} — sin contraseñas.', 'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda su propio plan, entrenamientos y peso corporal.', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 9b1de44..40ee431 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Se connecter avec une passkey', 'Create new profile': 'Créer un nouveau profil', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ce navigateur ne prend pas en charge les passkeys — tu peux quand même utiliser openGym localement sur cet appareil.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ce navigateur ne prend pas en charge les passkeys, et ce serveur exige un compte. Essaie un navigateur ou un appareil compatible avec les passkeys.', 'Continue without account': 'Continuer sans compte', 'Passkeys use {0} — no passwords.': 'Les passkeys utilisent {0} — pas de mots de passe.', 'Each profile keeps its own plan, workouts & body weight.': 'Chaque profil garde son plan, ses séances et son poids corporel.', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 163cb93..08b9c01 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'पासकी से साइन इन करें', 'Create new profile': 'नई प्रोफ़ाइल बनाएँ', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता — फिर भी आप इस डिवाइस पर openGym लोकली इस्तेमाल कर सकते हैं।', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता, और इस सर्वर के लिए खाता ज़रूरी है। पासकी सपोर्ट वाला ब्राउज़र या डिवाइस आज़माएँ।', 'Continue without account': 'बिना खाते के जारी रखें', 'Passkeys use {0} — no passwords.': 'पासकी {0} का उपयोग करती हैं — कोई पासवर्ड नहीं।', 'Each profile keeps its own plan, workouts & body weight.': 'हर प्रोफ़ाइल की अपनी योजना, वर्कआउट और वज़न होते हैं।', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index af73182..f729872 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Accedi con passkey', 'Create new profile': 'Crea nuovo profilo', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Questo browser non supporta le passkey — puoi comunque usare openGym localmente su questo dispositivo.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Questo browser non supporta le passkey e questo server richiede un account. Prova un browser o un dispositivo che supporti le passkey.', 'Continue without account': 'Continua senza account', 'Passkeys use {0} — no passwords.': 'Le passkey usano {0} — niente password.', 'Each profile keeps its own plan, workouts & body weight.': 'Ogni profilo ha il proprio piano, allenamenti e peso corporeo.', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index c6a6431..4c02ef8 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': '패스키로 로그인', 'Create new profile': '새 프로필 만들기', "This browser doesn't support passkeys — you can still use openGym locally on this device.": '이 브라우저는 패스키를 지원하지 않아요 — 그래도 이 기기에서 openGym을 로컬로 사용할 수 있습니다.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '이 브라우저는 패스키를 지원하지 않고, 이 서버는 계정이 필요합니다. 패스키를 지원하는 브라우저나 기기를 사용해 보세요.', 'Continue without account': '계정 없이 계속', 'Passkeys use {0} — no passwords.': '패스키는 {0}을(를) 사용합니다 — 비밀번호 없음.', 'Each profile keeps its own plan, workouts & body weight.': '프로필마다 자신의 계획, 운동, 체중을 보관합니다.', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 5d0fc10..f94057d 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Zaloguj się passkey', 'Create new profile': 'Utwórz nowy profil', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Ta przeglądarka nie obsługuje passkey — mimo to możesz używać openGym lokalnie na tym urządzeniu.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ta przeglądarka nie obsługuje passkey, a ten serwer wymaga konta. Spróbuj przeglądarki lub urządzenia z obsługą passkey.', 'Continue without account': 'Kontynuuj bez konta', 'Passkeys use {0} — no passwords.': 'Passkey używa: {0} — bez haseł.', 'Each profile keeps its own plan, workouts & body weight.': 'Każdy profil ma własny plan, treningi i masę ciała.', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index e7e9d0c..590d2ec 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Entrar com passkey', 'Create new profile': 'Criar novo perfil', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador não suporta passkeys — ainda assim podes usar o openGym localmente neste dispositivo.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador não suporta passkeys e este servidor exige uma conta. Experimenta um navegador ou dispositivo com suporte a passkeys.', 'Continue without account': 'Continuar sem conta', 'Passkeys use {0} — no passwords.': 'As passkeys usam {0} — sem palavras-passe.', 'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda o seu plano, treinos e peso corporal.', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 98a9a7c..2265f91 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Войти по ключу доступа', 'Create new profile': 'Создать новый профиль', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Этот браузер не поддерживает ключи доступа — но openGym можно использовать локально на этом устройстве.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Этот браузер не поддерживает ключи доступа, а на этом сервере нужен аккаунт. Попробуйте браузер или устройство с поддержкой ключей доступа.', 'Continue without account': 'Продолжить без аккаунта', 'Passkeys use {0} — no passwords.': 'Ключи доступа используют {0} — без паролей.', 'Each profile keeps its own plan, workouts & body weight.': 'У каждого профиля свой план, тренировки и вес тела.', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index a5853bf..fd4fb34 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': 'Geçiş anahtarıyla giriş yap', 'Create new profile': 'Yeni profil oluştur', "This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor — yine de openGym’i bu cihazda yerel olarak kullanabilirsin.', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor ve bu sunucu bir hesap gerektiriyor. Geçiş anahtarı destekleyen bir tarayıcı veya cihaz dene.', 'Continue without account': 'Hesapsız devam et', 'Passkeys use {0} — no passwords.': 'Geçiş anahtarları {0} kullanır — şifre yok.', 'Each profile keeps its own plan, workouts & body weight.': 'Her profilin kendi planı, antrenmanları ve vücut ağırlığı vardır.', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 518427a..55defc0 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -223,6 +223,7 @@ export default { 'Sign in with passkey': '用通行密钥登录', 'Create new profile': '创建新档案', "This browser doesn't support passkeys — you can still use openGym locally on this device.": '此浏览器不支持通行密钥——你仍可在本设备上本地使用 openGym。', + "This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '此浏览器不支持通行密钥,且此服务器需要账户。请换用支持通行密钥的浏览器或设备。', 'Continue without account': '不用账号继续', 'Passkeys use {0} — no passwords.': '通行密钥使用{0}——没有密码。', 'Each profile keeps its own plan, workouts & body weight.': '每个档案有自己的计划、训练和体重。', diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 2b41633..6da600e 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -3,6 +3,7 @@ import { api } from '../lib/api.js' import { localTZ } from '../lib/format.js' import { registerCustom } from '../lib/exercises.js' import { DEMO, DEMO_SEEDED } from '../lib/demo.js' +import { guestAllowed } from '../lib/guest.js' import { MOBILE, nativeLoad, nativeSave, syncReminder } from '../lib/mobile.js' const KEY = 'gym_state_v1' @@ -95,6 +96,16 @@ export const useStore = create((set, get) => { isGuest: () => localStorage.getItem('gym_guest') === '1', setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) }, + // Public config from /api/config (invite_only, allow_guest). null until the first successful + // fetch — the login screen and boot both read it, so it is fetched once and cached here + // rather than by each screen that happens to need it. + config: null, + async loadConfig() { + if (get().config) return get().config + try { const c = await api('/api/config'); set({ config: c }); return c } + catch { return null } + }, + setUser(u) { if (u) { localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest') } else localStorage.removeItem('gym_user') @@ -172,6 +183,12 @@ export const useStore = create((set, get) => { set({ ready: true }) return } + // Guests never authenticate, so an instance that turned guest mode off has no request to + // refuse — the only way the switch reaches someone already inside is here, on their next + // boot. Ending the session needs a positive `allow_guest: false`; see lib/guest.js for why + // an unreachable server must not be allowed to lock anyone out (#42). + const cfg = await get().loadConfig() + if (!guestAllowed(cfg)) get().setGuest(false) try { const me = await api('/api/me') get().setUser(me.user) diff --git a/frontend/src/views/Login.jsx b/frontend/src/views/Login.jsx index 43fe940..0df9748 100644 --- a/frontend/src/views/Login.jsx +++ b/frontend/src/views/Login.jsx @@ -1,21 +1,25 @@ import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' -import { webauthnOK, passkeyLogin, passkeyRegister, api, BIO } from '../lib/api.js' +import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js' import { hasData } from '../store/useStore.js' import { t } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' +import { guestAllowed } from '../lib/guest.js' import { useState, useRef, useEffect } from 'react' import Icon from '../components/Icon.jsx' import { Button } from '../components/ui.jsx' function RegisterSheet({ close }) { - const { setUser, pushState, pullState } = useStore() + const { setUser, pushState, pullState, loadConfig } = useStore() + const config = useStore(s => s.config) const [name, setName] = useState('') const [code, setCode] = useState('') - const [inviteOnly, setInviteOnly] = useState(false) + const inviteOnly = !!config?.invite_only const ref = useRef(null) useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, []) - useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, []) + // Boot already fetched this; retry here only if that attempt failed, so the invite field still + // appears on an instance whose config arrived late rather than never. + useEffect(() => { loadConfig() }, [loadConfig]) const go = async () => { const n = name.trim() if (!n) { useUI.getState().toast(t('Enter a name')); return } @@ -44,6 +48,8 @@ function RegisterSheet({ close }) { export default function Login() { const { setUser, pullState, setGuest } = useStore() + const config = useStore(s => s.config) + const canGuest = guestAllowed(config) const signIn = async () => { try { const u = await passkeyLogin(); setUser(u); await pullState(); useUI.getState().toast(t('Welcome back, {0}', u.name)) } catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) } @@ -77,9 +83,13 @@ export default function Login() {
-
- :
{t("This browser doesn't support passkeys — you can still use openGym locally on this device.")}
} - + {canGuest &&
} + :
{canGuest + ? t("This browser doesn't support passkeys — you can still use openGym locally on this device.") + // Without passkeys and without the guest entrance there is no way in from this browser, + // so say that plainly instead of offering a local profile that cannot be created. + : t("This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.")}
} + {canGuest && }
{t('Passkeys use {0} — no passwords.', BIO)}
{t('Each profile keeps its own plan, workouts & body weight.')}
) From 86f3476f5fb36cc98c49d1d6c5cd8b7a1ca7e66c Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:02:38 +0200 Subject: [PATCH 19/58] fatigue: saturating volume-based model, no window cliff, reachable level bands --- frontend/src/lib/recovery.js | 21 ++++-- frontend/src/lib/recovery.test.js | 83 +++++++++++++++------- frontend/src/views/Stats.jsx | 4 +- frontend/src/views/Stats.recovery.test.jsx | 18 ++--- 4 files changed, 84 insertions(+), 42 deletions(-) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index 54a2793..ebc8020 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -2,7 +2,13 @@ import { EXIDX } from './exercises.js' import { MUSCLES, musclesOf } from './muscles.js' /** Completed-workout window used when calculating current fatigue. */ -export const FATIGUE_WINDOW_MS = 259200000 +// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve +// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting +// fatigue level without ever pinning it, and the value can then fade asymptotically. +export const FATIGUE_REF_VOLUME = 3 +// Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20 +// half-lives) a session contributes below 1e-6 to the accumulated value. +export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000 /** Exponential half-life for fatigue stimulus. */ export const FATIGUE_HALF_LIFE_MS = 129600000 @@ -89,16 +95,19 @@ function fatigueValue(events, now) { lastTimestamp = event.timestamp } value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) - return clamp(value, 0, 1) + // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts + // higher but never pins, and the value fades asymptotically - no window-edge cliff. + return 1 - Math.exp(-value / FATIGUE_REF_VOLUME) } /** * Calculate current per-muscle fatigue from completed sets in the recent window. * * Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed - * set contributes the exercise's `musclesOf` weights; sets exactly 72 hours old are excluded. - * Stimuli are accumulated chronologically with a 36-hour half-life, decayed to `now`, and - * clamped to [0, 1]. The result always contains every drawable muscle slug. + * set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for + * performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life, + * decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME). + * The result always contains every drawable muscle slug. * * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. * @param {number} now Current time in milliseconds; injected to keep this function deterministic. @@ -106,7 +115,7 @@ function fatigueValue(events, now) { */ export function fatigueOf(workouts, now) { const current = Number(now) - const cutoff = current - FATIGUE_WINDOW_MS + const cutoff = current - FATIGUE_SCAN_MS const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff) const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []])) for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus) diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js index 2d03dcf..0f0d35a 100644 --- a/frontend/src/lib/recovery.test.js +++ b/frontend/src/lib/recovery.test.js @@ -1,8 +1,9 @@ import { describe, expect, it } from 'vitest' import { FATIGUE_HALF_LIFE_MS, + FATIGUE_REF_VOLUME, + FATIGUE_SCAN_MS, FATIGUE_STATES, - FATIGUE_WINDOW_MS, STRENGTH_FLOOR, STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, @@ -53,7 +54,8 @@ const stableFloat = value => Number(value.toFixed(12)) describe('recovery constants', () => { it('exports the pinned windows, half-lives, floor, and state labels', () => { - expect(FATIGUE_WINDOW_MS).toBe(72 * HOUR) + expect(FATIGUE_REF_VOLUME).toBe(3) + expect(FATIGUE_SCAN_MS).toBe(30 * DAY) expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR) expect(STRENGTH_FULL_MS).toBe(14 * DAY) expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY) @@ -86,14 +88,29 @@ describe('fatigueOf and strengthOf', () => { for (const slug of MUSCLES) { const weight = WEIGHTED_WEIGHTS[slug] || 0 - expect(fatigue[slug]).toBe(weight) + expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10) expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR) } - expect(fatiguedMuscles(workouts, NOW)).toEqual( - Object.entries(WEIGHTED_WEIGHTS) - .filter(([, weight]) => weight > 0.5) - .map(([slug]) => slug), - ) + // one set never crosses the fatigued threshold on the saturating curve + expect(fatiguedMuscles(workouts, NOW)).toEqual([]) + }) + + it('raises starting fatigue with volume, never pins, and fades without a cliff', () => { + const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG] + expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10) + expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10) + expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10) + expect(at0(12)).toBeGreaterThan(at0(5)) + expect(at0(5)).toBeGreaterThan(at0(1)) + expect(at0(12)).toBeLessThan(1) + // one half-life later the gradient is still visible at any volume + const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG] + expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10) + expect(later).toBeLessThan(at0(12)) + // no cliff: 72h keeps decaying instead of snapping to zero + const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG] + expect(old).toBeGreaterThan(0) + expect(old).toBeLessThan(0.25) }) it('decays each weighted stimulus exactly at 36 hours and by sqrt-half at 18 hours', () => { @@ -101,18 +118,23 @@ describe('fatigueOf and strengthOf', () => { const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW) const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS) for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) { - expect(fatigue[slug]).toBeCloseTo(weight * expectedDecay, 12) + expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10) + } + if (age === FATIGUE_HALF_LIFE_MS) { + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10) } - if (age === FATIGUE_HALF_LIFE_MS) expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBe(0.5) if (age === FATIGUE_HALF_LIFE_MS / 2) { - expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(0.5 ** 0.5, 12) + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10) } } }) - it('excludes a completed set exactly at the strict 72-hour window edge', () => { - const workouts = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_WINDOW_MS)] - expect(fatigueOf(workouts, NOW)).toEqual(zeroFatigue()) + it('fades a 72-hour-old set below the ready threshold instead of hard-cutting', () => { + const workouts = [doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)] + const value = fatigueOf(workouts, NOW)[SINGLE_SLUG] + expect(value).toBeGreaterThan(0) + expect(value).toBeLessThan(0.25) + expect(fatigueStateOf(value)).toBe(FATIGUE_STATES.READY) expect(strengthOf(workouts, NOW)[SINGLE_SLUG]).toBe(1) }) @@ -126,11 +148,15 @@ describe('fatigueOf and strengthOf', () => { }) describe('fatigue state boundaries', () => { + // Inverse of the saturation curve: raw stimulus needed to land exactly on a target level. + const rawAt = target => -FATIGUE_REF_VOLUME * Math.log(1 - target) + it('classifies exactly .25 as recovering and .2499 as ready', () => { const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG] + const sets = 3 const valueAt = target => { - const age = FATIGUE_HALF_LIFE_MS * Math.log2(weight / target) - const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW)[SECONDARY_SLUG] + const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target)) + const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG] expect(value).toBeCloseTo(target, 10) return stableFloat(value) } @@ -140,15 +166,16 @@ describe('fatigue state boundaries', () => { }) it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => { - const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS)] + const sets = 3 + const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)] const aboveHalf = [ - doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(1 / 0.5001)), + doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets), ] const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG] const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG] - expect(half).toBe(0.5) - expect(fatigueStateOf(half)).toBe(FATIGUE_STATES.RECOVERING) + expect(half).toBeCloseTo(0.4999, 10) + expect(fatigueStateOf(stableFloat(half))).toBe(FATIGUE_STATES.RECOVERING) expect(fatiguedMuscles(atHalf, NOW)).toEqual([]) expect(above).toBeCloseTo(0.5001, 10) expect(fatigueStateOf(stableFloat(above))).toBe(FATIGUE_STATES.FATIGUED) @@ -179,22 +206,24 @@ describe('strengthOf', () => { }) describe('accumulation and purity', () => { - it('matches the sum of independently decayed stimuli in chronological order', () => { + it('matches the saturated sum of independently decayed stimuli in chronological order', () => { const ages = [64 * HOUR, 40 * HOUR] const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age)) - const expected = ages.reduce( + const raw = ages.reduce( (sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS), 0, ) + const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME) - expect(expected).toBeLessThan(1) - expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) - expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 12) + expect(raw).toBeLessThan(FATIGUE_REF_VOLUME) + expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) + expect(fatigueOf([...workouts].reverse(), NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) }) - it('clamps saturation and returns identical results without mutating inputs or sharing state', () => { + it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => { const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)] - expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBe(1) + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10) + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1) const workouts = [ doneWorkoutAt(SINGLE.id, NOW - 64 * HOUR), diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 3186f9c..af08fba 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -39,8 +39,10 @@ function latestMuscleTraining(workouts) { const FATIGUE_LEVELS = [ { at: 0, level: 0 }, + { at: 0.15, level: 1 }, { at: 0.25, level: 2 }, - { at: 0.5, level: 4, exclusive: true }, + { at: 0.4, level: 3 }, + { at: 0.55, level: 4, exclusive: true }, ] const STRENGTH_LEVELS = [ diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index 6bfc209..bf06701 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -71,8 +71,9 @@ function entry(id, sets) { } function lifecycleWorkouts(now = BASE_NOW) { - // The 36-hour fatigue edge crosses .5 after one 60-second interval tick. - const fatigueEdge = now - (36 * HOUR - 30000) + // A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge + // flips fatigued -> recovering after one 60-second interval tick. + const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * HOUR - 30000) // This completed set is in the initial 30-day Balance window, then ages out after one tick. const balanceEdge = now - (30 * DAY - 30000) // The 14-day strength edge becomes sub-full after one tick. @@ -81,7 +82,7 @@ function lifecycleWorkouts(now = BASE_NOW) { const absCompleted = now - 20 * DAY const absUndone = now - DAY return [ - workout('fatigue-edge', fatigueEdge, [entry('1254', [set(true, { rir: 0 })])]), + workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => set(true, { rir: 0 })))]), workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]), workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]), workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]), @@ -90,8 +91,9 @@ function lifecycleWorkouts(now = BASE_NOW) { } function allFatiguedWorkout(now = BASE_NOW) { - // Primary muscles have one completed set. The three secondary-only map slugs have two - // completed sets so their .4 weights are also above the production .5 fatigue boundary. + // Eight completed sets per exercise: on the saturating curve every involved muscle gets + // raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the + // catalogue's secondary-muscle metadata. const ids = [ ['1018', 1], // trapezius ['1012', 1], // deltoids @@ -111,7 +113,7 @@ function allFatiguedWorkout(now = BASE_NOW) { ['1000', 1], // calves ['1396', 2], // calves + tibialis ] - return workout('all-fatigued', now, ids.map(([id, count]) => entry(id, Array.from({ length: count }, () => set(true))))) + return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true))))) } function allSubfullWorkout(now = BASE_NOW) { @@ -226,7 +228,7 @@ describe('Stats muscle recovery view runtime', () => { expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() expect(lastMap().selected).toBe('chest') - expect(lastMap().load.chest).toBe(2) + expect(lastMap().load.chest).toBe(7) }) it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => { @@ -253,7 +255,7 @@ describe('Stats muscle recovery view runtime', () => { expect(strengthRows()).toContain('Quads') await click(viewButton('Muscle balance')) - expect(lastMap().load.chest).toBe(1) + expect(lastMap().load.chest).toBe(6) expectPressed(balanceRangeButton('30d')) }) From d0075eeddf668fa6f7f98b0111e97aedf5393b86 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:10:43 +0200 Subject: [PATCH 20/58] rest notification: service-worker path for Android, use existing string --- frontend/src/store/useUI.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js index 0330ee7..d1a121a 100644 --- a/frontend/src/store/useUI.js +++ b/frontend/src/store/useUI.js @@ -33,7 +33,14 @@ const maybeRestNotification = async () => { if (!document.hidden && document.visibilityState !== 'hidden') return if (Notification.permission !== 'granted' && !(await requestRestNotificationPermission())) return try { - new Notification(t('Rest over'), { body: t('Rest over — next set!') }) + // Android Chrome forbids the Notification constructor (Illegal constructor) - the + // service-worker registration path is the one that actually pops there. + const reg = await navigator.serviceWorker?.getRegistration?.() + if (reg?.showNotification) { + reg.showNotification(t('Rest over — next set!'), { body: t('Rest over — next set!') }) + return + } + new Notification(t('Rest over — next set!'), { body: t('Rest over — next set!') }) } catch { // Intentionally ignore: notification APIs vary by browser and policy in edge cases. } From 13ed730a0c1a09ea83abe14d4fedc3ff3847b09a Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 7 Aug 2026 11:35:04 +0200 Subject: [PATCH 21/58] Changelog v1.2.6: Muscle-Map-Recovery, Rest-Notification, Rear-Delt-Sekundaers --- CHANGELOG.md | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a28816..5937601 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,41 @@ ## v1.2.6 — 2026-08-07 -A freestyle session no longer starts from blanks, and a self-hosted instance can finally insist -that everyone using it has an account. +The muscle map learned to answer a second question — not just where the volume went, but what is +still recovering from it. Plus: a freestyle session no longer starts from blanks, the rest timer +can reach you in another app, and a self-hosted instance can insist that everyone using it has an +account. + +### The muscle map, read as recovery (#44) + +- 🔥 **A `Balance | Fatigue | Strength` switch on the Stats muscle card.** Balance is the map you + already had and is untouched. Fatigue shades each muscle by how much of the recent training it + is still carrying; Strength shades it by how long it has been since you trained it at all, with + the weeks-since count spelled out underneath. +- **Fatigue is volume-sensitive and fades smoothly.** A hard twelve-set chest day starts near the + top and takes about six days to read ready again; a single set barely registers and is gone in + two. It decays continuously on a 36-hour half-life rather than expiring at a window edge, so the + map never flips from "fatigued" to "ready" between one look and the next. +- **Strength holds for two weeks, then decays toward a floor.** A muscle you have not trained in + months reads detrained rather than absent, which is the state that actually tells you something. +- Both views are pure functions over your existing history — no new stored data, no schema change, + nothing sent anywhere. + +### The rest timer can reach you in another app (#49) + +- ⏰ **A system notification when rest is over**, on top of the beep, for when you have switched to + another tab or app mid-session. Permission is asked the first time a rest starts, and everything + degrades quietly where notifications are unsupported or refused. +- It goes through the service worker where the browser requires that — which is most phones — and + falls back to the direct API elsewhere. No new dependencies; the existing server push path is + untouched. + +### Rows now strain the rear delts (#51) + +- **Four row variations gained rear-deltoid secondaries** — barbell, dumbbell, inverted and cable + seated rows — so the muscle map spreads their load the way the lift actually does. The overrides + live in a small table that survives a regeneration of the exercise dataset rather than being + edited into the generated data. ### An instance can require an account (#42) From 577c86b487c5b91dda85ad8dd589379261f4e29f Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 13:12:42 +0200 Subject: [PATCH 22/58] derive secondary additions via smOf overlay - raw dataset never mutated --- frontend/src/lib/exercises.js | 15 ++++++++++----- frontend/src/lib/muscles.js | 4 ++-- frontend/src/lib/muscles.test.js | 13 ++++++++++++- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index 7f6adf4..f47cb88 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -13,12 +13,17 @@ const SECONDARY_ADDITIONS = { '0861': ['rear deltoids'], // cable seated row } +// Secondary muscles for an exercise, with the small conservative additions applied as an +// overlay. The raw dataset is never mutated - consumers that want the pristine catalogue +// (export, print, import) keep reading EXDB untouched, while the muscle map sees the +// enriched list. Values follow the dataset's existing alias vocabulary. +export const smOf = ex => { + const base = Array.isArray(ex?.sm) ? ex.sm : (ex?.sm ? [ex.sm] : []) + return [...new Set([...base, ...(SECONDARY_ADDITIONS[ex?.id] || [])])] +} + export const EXIDX = {} -EXDB.forEach(e => { - const additions = SECONDARY_ADDITIONS[e.id] - if (additions) e.sm = [...new Set([...(e.sm || []), ...additions])] - EXIDX[e.id] = e -}) +EXDB.forEach(e => { EXIDX[e.id] = e }) export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort() // Equipment options present in a given list of exercises, most common first (issue #6). diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index c744812..12cf5f5 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -7,7 +7,7 @@ // map can actually draw, via ALIAS below. Anything genuinely undrawable (hands, // ankles, "cardiovascular system") maps to null and is dropped rather than guessed at. -import { EXIDX } from './exercises.js' +import { EXIDX , smOf } from './exercises.js' // The muscles a map can shade, in head-to-toe order — also the order of any list // built from them, so "what am I neglecting" reads top-down like a body. @@ -78,7 +78,7 @@ export function musclesOf(ex) { if (slug) out[slug] = Math.max(out[slug] || 0, w) } add(ex.tg, 1) - ;(ex.sm || []).forEach(m => add(m, SECONDARY)) + ;smOf(ex).forEach(m => add(m, SECONDARY)) // Nothing recognised (custom exercises, or a target we don't draw) — use the body part. if (!Object.keys(out).length) Object.assign(out, BY_BODYPART[ex.bp] || {}) return out diff --git a/frontend/src/lib/muscles.test.js b/frontend/src/lib/muscles.test.js index 6d45dd5..3cde02e 100644 --- a/frontend/src/lib/muscles.test.js +++ b/frontend/src/lib/muscles.test.js @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { EXIDX } from './exercises.js' +import { EXIDX, EXDB, smOf } from './exercises.js' import { musclesOf } from './muscles.js' // The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps @@ -31,3 +31,14 @@ describe('catalogue secondary muscles', () => { } }) }) + + +describe('catalogue secondary additions', () => { + it('enriches the muscle map without mutating the raw dataset', () => { + const raw = EXDB.find(e => e.id === '0027') + expect(raw.sm).not.toContain('rear deltoids') + expect(smOf(raw)).toContain('rear deltoids') + // the alias collapses onto the deltoids slug in the canonical muscle map + expect(musclesOf(raw)).toHaveProperty('deltoids') + }) +}) From edb3e42c43e8336f24cb3994565e4d23dcfeb75a Mon Sep 17 00:00:00 2001 From: root Date: Thu, 6 Aug 2026 19:27:42 +0200 Subject: [PATCH 23/58] session UX: warm-up phase separation, add/remove warm-up sets, weight cascade to following sets --- frontend/src/index.css | 3 ++ frontend/src/locales/de.js | 2 ++ frontend/src/locales/es.js | 2 ++ frontend/src/locales/fr.js | 2 ++ frontend/src/locales/hi.js | 2 ++ frontend/src/locales/it.js | 2 ++ frontend/src/locales/ko.js | 2 ++ frontend/src/locales/pl.js | 2 ++ frontend/src/locales/pt.js | 2 ++ frontend/src/locales/ru.js | 2 ++ frontend/src/locales/tr.js | 2 ++ frontend/src/locales/zh.js | 2 ++ frontend/src/views/Workout.jsx | 64 ++++++++++++++++++++++++++-------- 13 files changed, 74 insertions(+), 15 deletions(-) diff --git a/frontend/src/index.css b/frontend/src/index.css index 024eebe..a6be108 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -559,6 +559,9 @@ h4.sec{ .setrow+.setrow::before{ content:'';position:absolute;left:32px;right:0;top:0;height:var(--hair);background:var(--sep); } +.setph{margin:8px 0 2px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--dim);display:flex;align-items:center;gap:10px} +.setph::after{content:'';flex:1;height:1px;background:var(--sep)} +.setsep{height:1px;background:var(--sep);margin:9px 0} .setrow .n{ width:24px;height:24px;border-radius:50%;background:var(--surface-2);color:var(--label-2); display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:500;flex:none; diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 6099b60..a09bdd6 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -161,6 +161,8 @@ export default { 'Last time you hit all reps — try {0}': 'Letztes Mal alle Wdh. geschafft — versuch {0}', 'Weights bumped to {0}': 'Gewichte auf {0} erhöht', 'Remove set': 'Satz entfernen', + 'Warm-up': 'Aufwärmen', + 'Add warm-up set': 'Aufwärmsatz hinzufügen', 'Add set': 'Satz hinzufügen', 'Cardio logged': 'Cardio eingetragen', 'Discard workout?': 'Training verwerfen?', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 2e96c8f..f26af19 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'La última vez completaste todas las reps — prueba {0}', 'Weights bumped to {0}': 'Pesos subidos a {0}', 'Remove set': 'Quitar serie', + 'Warm-up': 'Calentamiento', + 'Add warm-up set': 'Añadir serie de calentamiento', 'Add set': 'Añadir serie', 'Cardio logged': 'Cardio registrado', 'Discard workout?': '¿Descartar entrenamiento?', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 9b8b542..9333955 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'Toutes les reps réussies la dernière fois — essaie {0}', 'Weights bumped to {0}': 'Poids montés à {0}', 'Remove set': 'Retirer une série', + 'Warm-up': 'Échauffement', + 'Add warm-up set': 'Ajouter une série d’échauffement', 'Add set': 'Ajouter une série', 'Cardio logged': 'Cardio noté', 'Discard workout?': 'Abandonner la séance ?', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 32b8fd0..673870d 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'पिछली बार सारे रेप्स पूरे किए — {0} आज़माएँ', 'Weights bumped to {0}': 'वज़न बढ़ाकर {0} किया', 'Remove set': 'सेट हटाएँ', + 'Warm-up': 'वार्म-अप', + 'Add warm-up set': 'वार्म-अप सेट जोड़ें', 'Add set': 'सेट जोड़ें', 'Cardio logged': 'कार्डियो दर्ज हुआ', 'Discard workout?': 'वर्कआउट छोड़ें?', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index f20d849..7d1079a 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': "L'ultima volta hai completato tutte le rip. — prova {0}", 'Weights bumped to {0}': 'Pesi aumentati a {0}', 'Remove set': 'Rimuovi serie', + 'Warm-up': 'Riscaldamento', + 'Add warm-up set': 'Aggiungi serie di riscaldamento', 'Add set': 'Aggiungi serie', 'Cardio logged': 'Cardio registrato', 'Discard workout?': 'Scartare allenamento?', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 1ea8005..e26c81d 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': '지난번에 모든 횟수를 채웠어요 — {0}에 도전해 보세요', 'Weights bumped to {0}': '무게를 {0}(으)로 올렸어요', 'Remove set': '세트 빼기', + 'Warm-up': '워밍업', + 'Add warm-up set': '워밍업 세트 추가', 'Add set': '세트 추가', 'Cardio logged': '유산소 기록됨', 'Discard workout?': '운동을 버릴까요?', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 04499c1..648fa99 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'Ostatnio zrobiłeś wszystkie powtórzenia — spróbuj {0}', 'Weights bumped to {0}': 'Ciężary podniesione do {0}', 'Remove set': 'Usuń serię', + 'Warm-up': 'Rozgrzewka', + 'Add warm-up set': 'Dodaj serię rozgrzewkową', 'Add set': 'Dodaj serię', 'Cardio logged': 'Cardio zapisane', 'Discard workout?': 'Odrzucić trening?', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 560758d..fc0cec2 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'Da última vez completaste todas as reps — tenta {0}', 'Weights bumped to {0}': 'Pesos aumentados para {0}', 'Remove set': 'Remover série', + 'Warm-up': 'Aquecimento', + 'Add warm-up set': 'Adicionar série de aquecimento', 'Add set': 'Adicionar série', 'Cardio logged': 'Cardio registado', 'Discard workout?': 'Descartar treino?', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index cef3ef2..699259b 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'В прошлый раз все повторения сделаны — попробуй {0}', 'Weights bumped to {0}': 'Веса подняты до {0}', 'Remove set': 'Убрать подход', + 'Warm-up': 'Разминка', + 'Add warm-up set': 'Добавить разминочный подход', 'Add set': 'Добавить подход', 'Cardio logged': 'Кардио записано', 'Discard workout?': 'Отменить тренировку?', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index cdab886..dc63609 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': 'Geçen sefer tüm tekrarları yaptın — {0} dene', 'Weights bumped to {0}': 'Ağırlıklar {0} değerine çıkarıldı', 'Remove set': 'Set kaldır', + 'Warm-up': 'Isınma', + 'Add warm-up set': 'Isınma seti ekle', 'Add set': 'Set ekle', 'Cardio logged': 'Kardiyo kaydedildi', 'Discard workout?': 'Antrenman iptal edilsin mi?', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index b743d39..2d58a58 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -154,6 +154,8 @@ export default { 'Last time you hit all reps — try {0}': '上次完成了所有次数——试试 {0}', 'Weights bumped to {0}': '重量已提升到 {0}', 'Remove set': '减一组', + 'Warm-up': '热身', + 'Add warm-up set': '添加热身组', 'Add set': '加一组', 'Cardio logged': '有氧已记录', 'Discard workout?': '放弃训练?', diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index c81d26c..79397d8 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -54,7 +54,7 @@ function Elapsed({ start }) { } /* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */ -function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onStartTimed }) { +function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed }) { const S = useStore(s => s.S) const working = useUI(s => s.work) const entry = S.active.entries[entryIdx] @@ -131,19 +131,30 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
{col1.hd}{col2 && {col2.hd}}{col3 && {col3.hd}}{timed && }
- {entry.sets.map((s, i) =>
-
{i + 1}
- {cell(s, i, col1, 'w')} - {col2 && cell(s, i, col2, 'r')} - {col3 && cell(s, i, col3, 'eff')} - {/* A timed set is started, not typed: the timer counts the hold down and checks the - set off itself. The checkbox stays for anyone who timed it on their own watch. */} - {timed && } - onToggle(i)} /> -
)} + {entry.sets.map((s, i) => { + const warmBefore = i > 0 && !!entry.sets[i - 1].warmup + const isFirstWarmup = !!s.warmup && !warmBefore + return
+ {isFirstWarmup &&
{t('Warm-up')}
} + {!s.warmup && warmBefore &&
} +
+
{i + 1}
+ {cell(s, i, col1, 'w')} + {col2 && cell(s, i, col2, 'r')} + {col3 && cell(s, i, col3, 'eff')} + {/* A timed set is started, not typed: the timer counts the hold down and checks the + set off itself. The checkbox stays for anyone who timed it on their own watch. */} + {timed && } + {s.warmup && } + onToggle(i)} /> +
+
+ })}
-
+
+
@@ -172,6 +183,16 @@ function ActiveWorkout() { // what was actually logged — in the session, in history and in a backup. const setField = (idx, i, field, v) => mutEntry(idx, e => { if (v == null) delete e.sets[i][field]; else e.sets[i][field] = v + // Changing a weight cascades to the following sets of the same phase, so a + // heavier bar carries through the set instead of retyping every row. + if (field === 'w') { + const warm = !!e.sets[i].warmup + for (let j = i + 1; j < e.sets.length; j++) { + if (!!e.sets[j].warmup === warm) { + if (v == null) delete e.sets[j][field]; else e.sets[j][field] = v + } + } + } }) const modeAt = idx => modeOf({ ...(A.entries[idx].target || {}), id: A.entries[idx].id }) const addSet = idx => mutEntry(idx, e => { @@ -182,6 +203,19 @@ function ActiveWorkout() { else e.sets.push({ w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false }) }) const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() }) + const addWarmup = idx => mutEntry(idx, e => { + const firstWork = e.sets.findIndex(x => !x.warmup) + const at = firstWork === -1 ? e.sets.length : firstWork + const l = e.sets[at - 1] || e.sets[e.sets.length - 1] + const m = modeOf({ ...(e.target || {}), id: e.id }) + const warm = m === 'cardio' + ? { min: l ? l.min : (e.target.min || 20), speed: l ? l.speed : (e.target.speed || 8), done: false, warmup: true } + : m === 'time' + ? { sec: l ? l.sec : (e.target.sec || 45), w: l ? (l.w || 0) : (e.target.weight || 0), done: false, warmup: true } + : { w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false, warmup: true } + e.sets.splice(at, 0, warm) + }) + const removeSetAt = (idx, i) => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.splice(i, 1) }) // A timed set is held, not typed. The work timer records what was actually held — an early // finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then @@ -267,11 +301,11 @@ function ActiveWorkout() { {unit.map((idx, k) =>
{k > 0 &&
+
} toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onStartTimed={i => startTimed(idx, i)} /> + onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
)}
) : ( - toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onStartTimed={i => startTimed(cur, i)} /> + toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} /> )} :
{t('Freestyle workout — add your first exercise.')}
} From 0109857249a87b30c50144de5c6ff73b40c4a4d1 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:10:43 +0200 Subject: [PATCH 24/58] cascade: fixed-weight only, never overwrite done sets --- frontend/src/views/Workout.jsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 79397d8..14260e4 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -186,9 +186,11 @@ function ActiveWorkout() { // Changing a weight cascades to the following sets of the same phase, so a // heavier bar carries through the set instead of retyping every row. if (field === 'w') { + const cfg = e.target || e + if (cfg.weightPrescription?.kind === 'percentage') return const warm = !!e.sets[i].warmup for (let j = i + 1; j < e.sets.length; j++) { - if (!!e.sets[j].warmup === warm) { + if (!!e.sets[j].warmup === warm && !e.sets[j].done) { if (v == null) delete e.sets[j][field]; else e.sets[j][field] = v } } From cbb3630423cca1ae06cc6f84560e1676d1bbeeac Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:13:59 +0200 Subject: [PATCH 25/58] warm-up sets: excluded from 1RM and progression only (volume semantics kept); tests --- frontend/src/lib/onerm.js | 2 +- frontend/src/lib/onerm.test.js | 16 ++++++++++++++++ frontend/src/lib/progression.js | 8 ++++---- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/frontend/src/lib/onerm.js b/frontend/src/lib/onerm.js index daf9fae..c3a0b11 100644 --- a/frontend/src/lib/onerm.js +++ b/frontend/src/lib/onerm.js @@ -44,7 +44,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) { export function bestSetOf(entry, formula = DEFAULT_FORMULA) { let best = null ;(entry?.sets || []).forEach(s => { - if (!s.done) return + if (!s.done || s.warmup) return const est = estimate1RM(s.w, s.r, formula) if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) } }) diff --git a/frontend/src/lib/onerm.test.js b/frontend/src/lib/onerm.test.js index 3460bb2..57c6ec0 100644 --- a/frontend/src/lib/onerm.test.js +++ b/frontend/src/lib/onerm.test.js @@ -146,3 +146,19 @@ describe('is1RMRecord', () => { expect(is1RMRecord(S, 'bench', { id: 'bench', sets: [{ w: 200, r: 5, done: false }] })).toBeNull() }) }) + + +describe('warm-up sets and 1RM', () => { + const ENTRY = { id: 'warm-test', sets: [ + { w: 20, r: 8, done: true, warmup: true }, + { w: 80, r: 5, done: true }, + ] } + + it('does not let a ticked-off warm-up set set or raise the estimated 1RM', () => { + const working = { id: 'warm-test', sets: [{ w: 80, r: 5, done: true }] } + expect(bestSetOf(ENTRY)).toEqual(bestSetOf(working)) + expect(best1RM({ workouts: [{ entries: [ENTRY] }] }, 'warm-test')).toBe( + best1RM({ workouts: [{ entries: [working] }] }, 'warm-test'), + ) + }) +}) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 17825a8..6b01dc3 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -110,7 +110,7 @@ export function readSession(entry, fallback) { const held = sets.map(s => (s.done ? (s.sec || 0) : 0)) return { mode, goal, held, - weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), + weight: Math.max(0, ...sets.filter(s => s.done && !s.warmup).map(s => s.w || 0)), best: Math.max(0, ...held), ok: goal > 0 && enough && held.length > 0 && held.every(h => h >= goal) } @@ -119,7 +119,7 @@ export function readSession(entry, fallback) { const reps = sets.map(s => (s.done ? (s.r || 0) : 0)) return { mode, goal, reps, - weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), + weight: Math.max(0, ...sets.filter(s => s.done && !s.warmup).map(s => s.w || 0)), count: reps.length, // the dimension bodyweight work grows (#33) low: reps.length ? Math.min(...reps) : 0, amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set @@ -132,7 +132,7 @@ export function sessionsFor(S, exId, fallback) { const out = [] ;(S.workouts || []).forEach(w => { const entry = w.entries.find(e => e.id === exId) - if (entry && entry.sets.some(s => s.done)) out.push({ d: w.d, ...readSession(entry, fallback) }) + if (entry && entry.sets.some(s => s.done && !s.warmup)) out.push({ d: w.d, ...readSession(entry, fallback) }) }) return out } @@ -250,7 +250,7 @@ export function nextPrescription(S, cfg, routine) { export function applyPrescription(sets, p) { if (!p || p.kind === 'off' || p.kind === 'first') return sets const out = sets.map(s => { - if (s.done) return s + if (s.done && !s.warmup) return s const o = { ...s } if (p.weight != null) o.w = p.weight if (p.reps != null) o.r = p.reps From 9cc645c7555ded6b68cac50791dda1a2ceb731f8 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 09:14:55 +0200 Subject: [PATCH 26/58] fix warmup 1RM test equality --- frontend/src/lib/onerm.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/lib/onerm.test.js b/frontend/src/lib/onerm.test.js index 57c6ec0..59a4f9e 100644 --- a/frontend/src/lib/onerm.test.js +++ b/frontend/src/lib/onerm.test.js @@ -157,7 +157,7 @@ describe('warm-up sets and 1RM', () => { it('does not let a ticked-off warm-up set set or raise the estimated 1RM', () => { const working = { id: 'warm-test', sets: [{ w: 80, r: 5, done: true }] } expect(bestSetOf(ENTRY)).toEqual(bestSetOf(working)) - expect(best1RM({ workouts: [{ entries: [ENTRY] }] }, 'warm-test')).toBe( + expect(best1RM({ workouts: [{ entries: [ENTRY] }] }, 'warm-test')).toEqual( best1RM({ workouts: [{ entries: [working] }] }, 'warm-test'), ) }) From 86ac937d5d366301c16a79b66eb7d55091c5befa Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 13:56:51 +0200 Subject: [PATCH 27/58] warm-up carve-outs (effort ratio, muscle map), cascade/warmup row helpers with tests, dead guard removed, total+work set counts --- frontend/src/lib/effort.js | 2 +- frontend/src/lib/history.js | 46 +++++++++++++++++++++++++++ frontend/src/lib/history.test.js | 53 +++++++++++++++++++++++++++++++- frontend/src/lib/muscles.js | 4 +-- frontend/src/locales/de.js | 1 + frontend/src/locales/es.js | 1 + frontend/src/locales/fr.js | 1 + frontend/src/locales/hi.js | 1 + frontend/src/locales/it.js | 1 + frontend/src/locales/ko.js | 1 + frontend/src/locales/pl.js | 1 + frontend/src/locales/pt.js | 1 + frontend/src/locales/ru.js | 1 + frontend/src/locales/tr.js | 1 + frontend/src/locales/zh.js | 1 + frontend/src/sheets.jsx | 4 +-- frontend/src/views/Workout.jsx | 23 +++----------- 17 files changed, 118 insertions(+), 25 deletions(-) diff --git a/frontend/src/lib/effort.js b/frontend/src/lib/effort.js index 8f83d96..8865147 100644 --- a/frontend/src/lib/effort.js +++ b/frontend/src/lib/effort.js @@ -44,7 +44,7 @@ export const scaleName = kind => EFFORT[kind].hd function eachDoneSet(S, fn) { ;(S.workouts || []).forEach(w => (w.entries || []).forEach(e => - (e.sets || []).forEach(s => { if (s.done) fn(s, w, e) }))) + (e.sets || []).forEach(s => { if (s.done && !s.warmup) fn(s, w, e) }))) } // A window in days, counted back from now. 0 = everything, which is also what an empty diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index 71a1fa8..43251af 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -270,3 +270,49 @@ export function streakWeeks(S) { } return streak } + +/** + * Cascade a weight change forward: following sets of the same warm-up flag that are still + * undone take the new value (null deletes the key). Done sets are never rewritten. + */ +export function cascadeWeight(rows, from, value) { + const warm = !!rows[from]?.warmup + const next = rows.slice() + for (let j = from + 1; j < next.length; j++) { + if (!!next[j].warmup === warm && !next[j].done) { + if (value == null) delete next[j].w + else next[j].w = value + } + } + return next +} + +/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */ +export function insertWarmupRow(rows, mode, target) { + const firstWork = rows.findIndex(x => !x.warmup) + const at = firstWork === -1 ? rows.length : firstWork + const l = rows[at - 1] || rows[rows.length - 1] + const warm = mode === 'cardio' + ? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, warmup: true } + : mode === 'time' + ? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true } + : { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true } + const next = rows.slice() + next.splice(at, 0, warm) + return next +} + +/** Remove the row at `i`, never emptying the entry below one row. */ +export function removeRowAt(rows, i) { + if (rows.length <= 1) return rows.slice() + const next = rows.slice() + next.splice(i, 1) + return next +} + +/** Completed non-warm-up sets across a workout's entries. */ +export function workSetsDone(w) { + return (w?.entries || []).reduce( + (n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0, + ) +} diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 1b8a3d2..3bc2218 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep } from './history.js' +import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -478,3 +478,54 @@ describe('workoutVolume', () => { expect(workoutVolume(w)).toBe(0) }) }) + + +describe('session row helpers', () => { + it('cascadeWeight propagates to same-flag undone rows and never rewrites done sets', () => { + const rows = [ + { warmup: true, w: 20, done: true }, + { warmup: true, w: 20, done: false }, + { w: 60, done: true }, + { w: 60, done: false }, + { w: 60, done: false }, + ] + const next = cascadeWeight(rows, 2, 62.5) + expect(next[2].w).toBe(60) // done set untouched + expect(next[3].w).toBe(62.5) // same flag (work), undone + expect(next[4].w).toBe(62.5) // same flag (work), undone + expect(next[1].w).toBe(20) // different flag (warm-up) untouched + }) + + it('cascadeWeight deleting the weight removes the key from following undone rows only', () => { + const rows = [ + { w: 60, done: true }, + { w: 60, done: false }, + { w: 60, done: false }, + ] + const next = cascadeWeight(rows, 0, null) + expect(next[0].w).toBe(60) // done set untouched + expect('w' in next[1]).toBe(false) + expect('w' in next[2]).toBe(false) + }) + + it('insertWarmupRow inserts before the first work row and copies the last warm-up values', () => { + const rows = [ + { warmup: true, w: 20, r: 8, done: true }, + { warmup: true, w: 30, r: 8, done: false }, + { w: 60, r: 8, done: false }, + ] + const next = insertWarmupRow(rows, 'reps', { reps: 8 }) + expect(next.length).toBe(4) + expect(next[2].warmup).toBe(true) + expect(next[2].w).toBe(30) // copies the preceding warm-up + expect(next[3].w).toBe(60) // work row still after the warm-up block + }) + + it('removeRowAt never empties an entry below one row', () => { + expect(removeRowAt([{ w: 60 }], 0).length).toBe(1) + const rows = [{ w: 60 }, { w: 70 }] + const next = removeRowAt(rows, 0) + expect(next.length).toBe(1) + expect(next[0].w).toBe(70) + }) +}) diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index 32db0d9..08ec013 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -108,7 +108,7 @@ export function loadOf(items) { */ export const loadOfWorkouts = (workouts, pick) => loadOf((workouts || []).flatMap(w => - (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && (!pick || pick(s))).length })))) + (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length })))) /** Load a routine *would* produce, from its planned set counts. */ export const loadOfRoutine = routine => @@ -116,7 +116,7 @@ export const loadOfRoutine = routine => /** Load for a workout still in progress — the sets ticked so far. */ export const loadOfActive = active => - loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done).length }))) + loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length }))) /** * Shade buckets 0–4 per muscle. diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index a09bdd6..9d9872b 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -583,4 +583,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} Sätze mit {1} — Zeit für Zusatzgewicht oder eine schwerere Variante.', '{0} per side': '{0} pro Seite', 'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.', + '{0} sets · {1} work': '{0} Sätze · {1} Arbeit', } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index f26af19..7a1187b 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} series de {1}: toca añadir peso o pasar a una variante más difícil.', '{0} per side': '{0} por lado', 'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.', + '{0} sets · {1} work': '{0} series · {1} trabajo', } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 9333955..350451f 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — il est temps d’ajouter du poids ou de passer à une variante plus dure.', '{0} per side': '{0} par côté', 'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.', + '{0} sets · {1} work': '{0} séries · {1} travail', } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 673870d..9ad7a51 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{1} रेप्स के {0} सेट — अब वज़न बढ़ाने या किसी कठिन वैरिएशन पर जाने का समय।', '{0} per side': 'प्रति तरफ़ {0}', 'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।', + '{0} sets · {1} work': '{0} सेट · {1} काम', } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 7d1079a..87c32ae 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} serie da {1} — è ora di aggiungere peso o passare a una variante più difficile.', '{0} per side': '{0} per lato', 'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.', + '{0} sets · {1} work': '{0} serie · {1} lavoro', } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index e26c81d..8722548 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{1}회 {0}세트 — 이제 무게를 올리거나 더 어려운 동작으로 넘어가세요.', '{0} per side': '한쪽당 {0}회', 'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.', + '{0} sets · {1} work': '{0} 세트 · {1} 작업', } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 648fa99..a9d13d3 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} powt. — czas dodać ciężar albo przejść na trudniejszy wariant.', '{0} per side': '{0} na stronę', 'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.', + '{0} sets · {1} work': '{0} serii · {1} praca', } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index fc0cec2..b422895 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} séries de {1} — hora de acrescentar peso ou passar a uma variação mais difícil.', '{0} per side': '{0} por lado', 'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.', + '{0} sets · {1} work': '{0} séries · {1} trabalho', } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 699259b..fc9edd3 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} × {1} — пора добавить вес или перейти к более сложному варианту.', '{0} per side': '{0} на сторону', 'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.', + '{0} sets · {1} work': '{0} подходов · {1} рабочих', } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index dc63609..0b63741 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{1} tekrarlık {0} set — ağırlık ekleme ya da daha zor bir varyasyona geçme zamanı.', '{0} per side': 'Taraf başına {0}', 'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.', + '{0} sets · {1} work': '{0} set · {1} çalışma', } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 2d58a58..d9c7aea 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -566,4 +566,5 @@ export default { '{0} sets of {1} — time to add weight or move to a harder variation.': '{0} 组 × {1} 次——该加重量或换更难的变式了。', '{0} per side': '每侧 {0} 次', 'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。', + '{0} sets · {1} work': '{0} 组 · {1} 工作', } diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 39c8180..180faa1 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -3,7 +3,7 @@ import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js' import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' -import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps } from './lib/history.js' +import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js' import { beep, vibrate } from './lib/sound.js' import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js' import { nav } from './lib/nav.js' @@ -910,7 +910,7 @@ function FinishSummary({ w, prs, e1prs = [], close }) {
{t('Duration')}
{fmtDur(w.end - w.start)}
{t('Volume')}
{fmtVol(w.vol, st.unit)}
-
{t('Sets')}
{setsDone(w)}
+
{t('Sets')}
{t('{0} sets · {1} work', setsDone(w), workSetsDone(w))}
{t('PRs')}
{prs.length || '—'}
{(prs.length > 0 || e1prs.length > 0) &&
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 14260e4..11d83e9 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' -import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort } from '../lib/history.js' +import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt } from '../lib/history.js' import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' @@ -186,14 +186,7 @@ function ActiveWorkout() { // Changing a weight cascades to the following sets of the same phase, so a // heavier bar carries through the set instead of retyping every row. if (field === 'w') { - const cfg = e.target || e - if (cfg.weightPrescription?.kind === 'percentage') return - const warm = !!e.sets[i].warmup - for (let j = i + 1; j < e.sets.length; j++) { - if (!!e.sets[j].warmup === warm && !e.sets[j].done) { - if (v == null) delete e.sets[j][field]; else e.sets[j][field] = v - } - } + e.sets = cascadeWeight(e.sets, i, v) } }) const modeAt = idx => modeOf({ ...(A.entries[idx].target || {}), id: A.entries[idx].id }) @@ -206,18 +199,10 @@ function ActiveWorkout() { }) const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() }) const addWarmup = idx => mutEntry(idx, e => { - const firstWork = e.sets.findIndex(x => !x.warmup) - const at = firstWork === -1 ? e.sets.length : firstWork - const l = e.sets[at - 1] || e.sets[e.sets.length - 1] const m = modeOf({ ...(e.target || {}), id: e.id }) - const warm = m === 'cardio' - ? { min: l ? l.min : (e.target.min || 20), speed: l ? l.speed : (e.target.speed || 8), done: false, warmup: true } - : m === 'time' - ? { sec: l ? l.sec : (e.target.sec || 45), w: l ? (l.w || 0) : (e.target.weight || 0), done: false, warmup: true } - : { w: l ? l.w : 0, r: l ? l.r : e.target.reps, done: false, warmup: true } - e.sets.splice(at, 0, warm) + e.sets = insertWarmupRow(e.sets, m, e.target || {}) }) - const removeSetAt = (idx, i) => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.splice(i, 1) }) + const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) }) // A timed set is held, not typed. The work timer records what was actually held — an early // finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then From 01072ef5e3b659debb782d0d157801a171e56cc3 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 15:19:11 +0200 Subject: [PATCH 28/58] warm-up round 3: applyPrescription/readSession never touch warm-up rows; per-phase set numbering; regression tests --- frontend/src/lib/progression.js | 20 +++++++---- frontend/src/lib/progression.test.js | 53 ++++++++++++++++++++++++++++ frontend/src/views/Workout.jsx | 4 ++- 3 files changed, 69 insertions(+), 8 deletions(-) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 6b01dc3..17d0463 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -101,7 +101,9 @@ function deloadTo(cur, step) { export function readSession(entry, fallback) { const target = (entry && entry.target) || fallback || {} const mode = modeOf({ ...target, id: entry && entry.id }) - const sets = (entry && entry.sets) || [] + // Warm-up rows are prep, not the session: one filtered read beats guarding every consumer + // below (an undone warm-up otherwise poisons `ok` forever and its reps drag `low`/`count`). + const sets = ((entry && entry.sets) || []).filter(s => !s.warmup) const planned = target.sets || sets.length const enough = sets.length >= planned @@ -110,7 +112,7 @@ export function readSession(entry, fallback) { const held = sets.map(s => (s.done ? (s.sec || 0) : 0)) return { mode, goal, held, - weight: Math.max(0, ...sets.filter(s => s.done && !s.warmup).map(s => s.w || 0)), + weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), best: Math.max(0, ...held), ok: goal > 0 && enough && held.length > 0 && held.every(h => h >= goal) } @@ -119,7 +121,7 @@ export function readSession(entry, fallback) { const reps = sets.map(s => (s.done ? (s.r || 0) : 0)) return { mode, goal, reps, - weight: Math.max(0, ...sets.filter(s => s.done && !s.warmup).map(s => s.w || 0)), + weight: Math.max(0, ...sets.filter(s => s.done).map(s => s.w || 0)), count: reps.length, // the dimension bodyweight work grows (#33) low: reps.length ? Math.min(...reps) : 0, amrap: reps.length ? reps[reps.length - 1] : 0, // Greyskull's final set @@ -250,7 +252,10 @@ export function nextPrescription(S, cfg, routine) { export function applyPrescription(sets, p) { if (!p || p.kind === 'off' || p.kind === 'first') return sets const out = sets.map(s => { - if (s.done && !s.warmup) return s + // Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to + // the work rows only (a ticked warm-up falling through here would be the data-loss the + // cascade fix removed, two files over). + if (s.done || s.warmup) return s const o = { ...s } if (p.weight != null) o.w = p.weight if (p.reps != null) o.r = p.reps @@ -260,9 +265,10 @@ export function applyPrescription(sets, p) { // A policy that decided on a set count gets to grow the list — bodyweight progression adds // a set where a barbell would have added a plate. Only ever upwards, and only by copying a // row that is already there: a session in progress must not lose a set it has logged. - if (p.sets > out.length) { - const seed = out[out.length - 1] - while (out.length < p.sets) out.push({ ...seed, done: false }) + const workRows = out.filter(s => !s.warmup) + if (p.sets > workRows.length) { + const seed = workRows[workRows.length - 1] || out[out.length - 1] + while (out.filter(s => !s.warmup).length < p.sets) out.push({ ...seed, done: false }) } return out } diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js index e3689aa..315f016 100644 --- a/frontend/src/lib/progression.test.js +++ b/frontend/src/lib/progression.test.js @@ -450,3 +450,56 @@ describe('applyPrescription', () => { expect(applyPrescription(sets, { kind: 'up', weight: 60, sets: 1 })).toHaveLength(sets.length) }) }) + + +describe('warm-up rows in session reads (round 3)', () => { + it('readSession ignores warm-up rows for reps, count, low and ok', () => { + // An undone warm-up (r 0) must not poison `ok` forever; its lighter reps must not + // drag `low`/`count` - the warm-up is prep, the session is the work rows. + const s = readSession({ id: LIFT, target: { sets: 2, reps: 5, mode: 'reps' }, sets: [ + { w: 20, r: 8, done: true, warmup: true }, + { w: 60, r: 5, done: true }, + { w: 60, r: 6, done: true }, + ] }) + expect(s.count).toBe(2) + expect(s.low).toBe(5) + expect(s.reps).toEqual([5, 6]) + expect(s.ok).toBe(true) + }) + + it('readSession keeps an undone warm-up out of held/ok in time mode', () => { + const s = readSession({ id: LIFT, target: { sets: 2, sec: 45, mode: 'time' }, sets: [ + { sec: 45, done: true, warmup: true }, + { sec: 45, done: true }, + { sec: 30, done: true }, + ] }) + expect(s.held).toEqual([45, 30]) + expect(s.ok).toBe(false) // the 30s work row is the miss, not the warm-up + }) +}) + +describe('applyPrescription never touches warm-up rows (round 3)', () => { + it('leaves a done warm-up exactly as logged', () => { + const sets = [ + { w: 20, r: 8, done: true, warmup: true }, + { w: 60, r: 5, done: true }, + { w: 60, r: 5, done: false }, + ] + const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5 }) + expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true }) + expect(out[1]).toEqual({ w: 60, r: 5, done: true }) + expect(out[2]).toEqual({ w: 62.5, r: 5, done: false }) + }) + + it('grows the work rows, not the warm-up rows, when the policy adds sets', () => { + const sets = [ + { w: 20, r: 8, done: true, warmup: true }, + { w: 60, r: 5, done: true }, + { w: 60, r: 5, done: false }, + ] + const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 }) + expect(out.filter(s => !s.warmup)).toHaveLength(4) // 2 existing + 2 grown + expect(out.filter(s => s.warmup)).toHaveLength(1) // warm-up untouched + expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true }) + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 11d83e9..2b1a2fd 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -134,11 +134,13 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov {entry.sets.map((s, i) => { const warmBefore = i > 0 && !!entry.sets[i - 1].warmup const isFirstWarmup = !!s.warmup && !warmBefore + // Numbering restarts per phase: with two warm-ups the first work set reads 1, not 3. + const phaseNum = entry.sets.slice(0, i + 1).filter(x => (x.warmup === true) === (s.warmup === true)).length return
{isFirstWarmup &&
{t('Warm-up')}
} {!s.warmup && warmBefore &&
}
-
{i + 1}
+
{phaseNum}
{cell(s, i, col1, 'w')} {col2 && cell(s, i, col2, 'r')} {col3 && cell(s, i, col3, 'eff')} From bee9b64b78da853fc126419bb153b549b62d06a2 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 7 Aug 2026 17:03:57 +0200 Subject: [PATCH 29/58] progression: guard set growth against an all-warm-up entry (no work seed, no infinite loop) --- frontend/src/lib/progression.js | 5 ++++- frontend/src/lib/progression.test.js | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index 17d0463..aa613d0 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -267,7 +267,10 @@ export function applyPrescription(sets, p) { // row that is already there: a session in progress must not lose a set it has logged. const workRows = out.filter(s => !s.warmup) if (p.sets > workRows.length) { - const seed = workRows[workRows.length - 1] || out[out.length - 1] + // An all-warm-up entry has no work row to seed growth from - growing warm-up copies + // would both invent work and never terminate the loop. Leave the entry untouched. + if (!workRows.length) return out + const seed = workRows[workRows.length - 1] while (out.filter(s => !s.warmup).length < p.sets) out.push({ ...seed, done: false }) } return out diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js index 315f016..b1857fd 100644 --- a/frontend/src/lib/progression.test.js +++ b/frontend/src/lib/progression.test.js @@ -502,4 +502,13 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => { expect(out.filter(s => s.warmup)).toHaveLength(1) // warm-up untouched expect(out[0]).toEqual({ w: 20, r: 8, done: true, warmup: true }) }) + + it('an all-warm-up entry terminates and stays untouched', () => { + const sets = [ + { w: 20, r: 8, done: true, warmup: true }, + { w: 25, r: 6, done: true, warmup: true }, + ] + const out = applyPrescription(sets, { kind: 'up', weight: 62.5, reps: 5, sets: 4 }) + expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop + }) }) From b29a3f6bb0e1eb8be7a4bc33cbbfaf07359e3c71 Mon Sep 17 00:00:00 2001 From: Space_Hermes Date: Fri, 7 Aug 2026 15:03:42 +0200 Subject: [PATCH 30/58] feat: create and remove session supersets --- frontend/node_modules | 1 + frontend/src/lib/history.js | 54 ++++++++++++++++++++++++++++++++ frontend/src/lib/history.test.js | 45 +++++++++++++++++++++++++- frontend/src/views/Workout.jsx | 23 +++++++++++--- 4 files changed, 118 insertions(+), 5 deletions(-) create mode 120000 frontend/node_modules diff --git a/frontend/node_modules b/frontend/node_modules new file mode 120000 index 0000000..41b9e25 --- /dev/null +++ b/frontend/node_modules @@ -0,0 +1 @@ +/tailnet-share/personal/projects/openGym/frontend/node_modules \ No newline at end of file diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index 43251af..d261345 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -142,6 +142,60 @@ export function cleanupSg(ex) { }) } +// Return the contiguous run around an entry that shares its superset id. A repeated id in a +// separated part of the list is deliberately not included: the display semantics are adjacent +// entries sharing one id, not every entry that happens to carry that id. +function contiguousSgGroup(items, idx) { + const sg = items[idx]?.sg + if (!sg) return [idx] + let first = idx + let last = idx + while (first > 0 && items[first - 1]?.sg === sg) first-- + while (last + 1 < items.length && items[last + 1]?.sg === sg) last++ + return Array.from({ length: last - first + 1 }, (_, i) => first + i) +} + +function freshSg(items, first, second) { + const base = `sg-${Math.min(first, second)}-${Math.max(first, second)}` + let sg = base + let n = 2 + while (items.some(e => e.sg === sg)) sg = `${base}-${n++}` + return sg +} + +// Purely pair two adjacent entries. Existing contiguous groups on either side are merged, so +// pairing the end of one group with the start of another produces one display unit. A caller can +// provide a group id (useful when restoring a known id); otherwise an existing id is preferred, +// with a deterministic unused id for two previously ungrouped entries. +export function pairAdjacent(items, first, second, groupId) { + if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array') + if (!Number.isInteger(first) || !Number.isInteger(second) || !items[first] || !items[second]) { + throw new RangeError('Superset entry indexes are invalid') + } + if (Math.abs(first - second) !== 1) throw new RangeError('Superset entries must be adjacent') + + const next = items.map(e => ({ ...e })) + const left = Math.min(first, second) + const right = Math.max(first, second) + const group = groupId || next[left].sg || next[right].sg || freshSg(next, left, right) + const members = new Set([...contiguousSgGroup(next, left), ...contiguousSgGroup(next, right)]) + members.forEach(i => { next[i].sg = group }) + return next +} + +// Remove one entry from its superset and clean any ids that no longer have an adjacent partner. +// This is pure so the active workout can replace its entries atomically through the store. +export function unpairSuperset(items, idx) { + if (!Array.isArray(items)) throw new TypeError('Superset entries must be an array') + if (!Number.isInteger(idx) || !items[idx]) throw new RangeError('Superset entry index is invalid') + const next = items.map(e => ({ ...e })) + delete next[idx].sg + next.forEach((e, i) => { + if (e.sg && !(next[i - 1]?.sg === e.sg || next[i + 1]?.sg === e.sg)) delete e.sg + }) + return next +} + export function lastEntryFor(S, exId) { for (let i = S.workouts.length - 1; i >= 0; i--) { const en = S.workouts[i].entries.find(e => e.id === exId) diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 3bc2218..68d1f0a 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt } from './history.js' +import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -9,6 +9,49 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').id const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id const BW = EXDB.find(e => e.eq === 'body weight').id +describe('superset editing', () => { + it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + + const paired = pairAdjacent(entries, 1, 2, 'sg-new') + + expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }]) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + expect(supersetUnits(paired)).toEqual([[0], [1, 2]]) + }) + + it('merges both contiguous groups when their boundary entries are paired', () => { + const entries = [ + { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' }, + { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' } + ] + + const merged = pairAdjacent(entries, 1, 2) + + expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left']) + expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right']) + }) + + it('unpairs one entry and removes sg values left without an adjacent partner', () => { + const entries = [ + { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' }, + { id: 'd', sg: 'orphan' } + ] + + const unpaired = unpairSuperset(entries, 1) + + expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]) + expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan']) + }) + + it('rejects a non-adjacent pairing request', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + + expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + }) +}) + describe('modeOf', () => { it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => { expect(modeOf({ id: CARDIO })).toBe('cardio') diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 2b1a2fd..28cc9e6 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' -import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt } from '../lib/history.js' +import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset } from '../lib/history.js' import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' @@ -54,7 +54,7 @@ function Elapsed({ start }) { } /* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */ -function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed }) { +function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) { const S = useStore(s => s.S) const working = useUI(s => s.work) const entry = S.active.entries[entryIdx] @@ -114,6 +114,10 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
{ex.n}
+ {!compact && (onPairPrev || onPairNext) &&
+ {onPairPrev && } + {onPairNext && } +
}
{cardio && {t('Cardio')}} {/* You log the total; this is the split, so the set in front of you is unambiguous @@ -205,6 +209,14 @@ function ActiveWorkout() { e.sets = insertWarmupRow(e.sets, m, e.target || {}) }) const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) }) + const pairAt = (first, second) => update(s => { + s.active.entries = pairAdjacent(s.active.entries, first, second) + }) + const unpairAt = idx => update(s => { + s.active.entries = unpairSuperset(s.active.entries, idx) + }) + const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null + const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null // A timed set is held, not typed. The work timer records what was actually held — an early // finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then @@ -286,7 +298,10 @@ function ActiveWorkout() {
{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}
{isSuperset ? (
-
{t('Superset · do these back-to-back, rest after both')}
+
+ {t('Superset · do these back-to-back, rest after both')} + +
{unit.map((idx, k) =>
{k > 0 &&
+
} )}
) : ( - toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} /> + toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} /> )} :
{t('Freestyle workout — add your first exercise.')}
} From 8bbf59c001dea2ba37f781f7dc55db8b40a9ce10 Mon Sep 17 00:00:00 2001 From: root Date: Sat, 8 Aug 2026 10:09:49 +0200 Subject: [PATCH 31/58] remove accidentally committed node_modules symlink --- .gitignore | 1 + frontend/node_modules | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 120000 frontend/node_modules diff --git a/.gitignore b/.gitignore index 12881fa..06bdf38 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ frontend/dist/ node_modules/ *.log .DS_Store +node_modules diff --git a/frontend/node_modules b/frontend/node_modules deleted file mode 120000 index 41b9e25..0000000 --- a/frontend/node_modules +++ /dev/null @@ -1 +0,0 @@ -/tailnet-share/personal/projects/openGym/frontend/node_modules \ No newline at end of file From 030a609427a9605aad22c561ac154b353b4dcc61 Mon Sep 17 00:00:00 2001 From: root Date: Sat, 8 Aug 2026 10:11:26 +0200 Subject: [PATCH 32/58] translate superset action labels (11 locales) --- frontend/src/locales/de.js | 3 +++ frontend/src/locales/es.js | 3 +++ frontend/src/locales/fr.js | 3 +++ frontend/src/locales/hi.js | 3 +++ frontend/src/locales/it.js | 3 +++ frontend/src/locales/ko.js | 3 +++ frontend/src/locales/pl.js | 3 +++ frontend/src/locales/pt.js | 3 +++ frontend/src/locales/ru.js | 3 +++ frontend/src/locales/tr.js | 3 +++ frontend/src/locales/zh.js | 3 +++ 11 files changed, 33 insertions(+) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 9d9872b..29630f7 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -584,4 +584,7 @@ export default { '{0} per side': '{0} pro Seite', 'You still log the total: {0} is {1} per side.': 'Du trägst weiterhin die Gesamtzahl ein: {0} sind {1} pro Seite.', '{0} sets · {1} work': '{0} Sätze · {1} Arbeit', + 'Make superset with previous': 'Mit vorheriger Übung kombinieren', + 'Make superset with next': 'Mit nächster Übung kombinieren', + 'Unpair': 'Trennen' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 7a1187b..b1fd37d 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} por lado', 'You still log the total: {0} is {1} per side.': 'Sigues registrando el total: {0} son {1} por lado.', '{0} sets · {1} work': '{0} series · {1} trabajo', + 'Make superset with previous': 'Hacer superserie con anterior', + 'Make superset with next': 'Hacer superserie con siguiente', + 'Unpair': 'Desvincular' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 350451f..e3d91d9 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} par côté', 'You still log the total: {0} is {1} per side.': 'Tu notes toujours le total : {0}, c’est {1} par côté.', '{0} sets · {1} work': '{0} séries · {1} travail', + 'Make superset with previous': 'Faire un superset avec le précédent', + 'Make superset with next': 'Faire un superset avec le suivant', + 'Unpair': 'Dissocier' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 9ad7a51..9e05cfe 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -567,4 +567,7 @@ export default { '{0} per side': 'प्रति तरफ़ {0}', 'You still log the total: {0} is {1} per side.': 'आप कुल ही दर्ज करते हैं: {0} यानी प्रति तरफ़ {1}।', '{0} sets · {1} work': '{0} सेट · {1} काम', + 'Make superset with previous': 'पिछले के साथ सुपरसेट', + 'Make superset with next': 'अगले के साथ सुपरसेट', + 'Unpair': 'अलग करें' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 87c32ae..a4b21bd 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} per lato', 'You still log the total: {0} is {1} per side.': 'Registri sempre il totale: {0} sono {1} per lato.', '{0} sets · {1} work': '{0} serie · {1} lavoro', + 'Make superset with previous': 'Superset con il precedente', + 'Make superset with next': 'Superset con il successivo', + 'Unpair': 'Separa' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 8722548..c309e6a 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -567,4 +567,7 @@ export default { '{0} per side': '한쪽당 {0}회', 'You still log the total: {0} is {1} per side.': '기록은 그대로 합계로 합니다: {0}회는 한쪽당 {1}회입니다.', '{0} sets · {1} work': '{0} 세트 · {1} 작업', + 'Make superset with previous': '이전 운동과 슈퍼셋', + 'Make superset with next': '다음 운동과 슈퍼셋', + 'Unpair': '분리' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index a9d13d3..568d0dc 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} na stronę', 'You still log the total: {0} is {1} per side.': 'Nadal zapisujesz łączną liczbę: {0} to {1} na stronę.', '{0} sets · {1} work': '{0} serii · {1} praca', + 'Make superset with previous': 'Połącz z poprzednim', + 'Make superset with next': 'Połącz z następnym', + 'Unpair': 'Rozłącz' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index b422895..006d63d 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} por lado', 'You still log the total: {0} is {1} per side.': 'Continuas a registar o total: {0} são {1} por lado.', '{0} sets · {1} work': '{0} séries · {1} trabalho', + 'Make superset with previous': 'Fazer superset com o anterior', + 'Make superset with next': 'Fazer superset com o próximo', + 'Unpair': 'Desfazer' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index fc9edd3..bb2a735 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -567,4 +567,7 @@ export default { '{0} per side': '{0} на сторону', 'You still log the total: {0} is {1} per side.': 'Ты по-прежнему записываешь общее число: {0} — это {1} на сторону.', '{0} sets · {1} work': '{0} подходов · {1} рабочих', + 'Make superset with previous': 'Суперсет с предыдущим', + 'Make superset with next': 'Суперсет со следующим', + 'Unpair': 'Разъединить' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 0b63741..d1a2147 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -567,4 +567,7 @@ export default { '{0} per side': 'Taraf başına {0}', 'You still log the total: {0} is {1} per side.': 'Toplamı kaydetmeye devam ediyorsun: {0}, taraf başına {1} demek.', '{0} sets · {1} work': '{0} set · {1} çalışma', + 'Make superset with previous': 'Öncekiyle superset yap', + 'Make superset with next': 'Sonrakiyle superset yap', + 'Unpair': 'Ayır' } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index d9c7aea..37b6a72 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -567,4 +567,7 @@ export default { '{0} per side': '每侧 {0} 次', 'You still log the total: {0} is {1} per side.': '你记录的仍然是总数:{0} 表示每侧 {1} 次。', '{0} sets · {1} work': '{0} 组 · {1} 工作', + 'Make superset with previous': '与上一个组成超级组', + 'Make superset with next': '与下一个组成超级组', + 'Unpair': '取消组合' } From 15c29029c17c3e618bf47376c64ee24cec53350b Mon Sep 17 00:00:00 2001 From: root Date: Sat, 8 Aug 2026 10:46:43 +0200 Subject: [PATCH 33/58] neutral superset header text (mirror live) --- frontend/src/locales/de.js | 2 +- frontend/src/locales/es.js | 2 +- frontend/src/locales/fr.js | 2 +- frontend/src/locales/hi.js | 2 +- frontend/src/locales/it.js | 2 +- frontend/src/locales/ko.js | 2 +- frontend/src/locales/pl.js | 2 +- frontend/src/locales/pt.js | 2 +- frontend/src/locales/ru.js | 2 +- frontend/src/locales/tr.js | 2 +- frontend/src/locales/zh.js | 2 +- frontend/src/views/Workout.jsx | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 29630f7..779b301 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -169,7 +169,7 @@ export default { 'The sets you logged in this session will be lost.': 'Die in dieser Einheit eingetragenen Sätze gehen verloren.', 'Superset {0} / {1}': 'Supersatz {0} / {1}', 'Exercise {0} / {1}': 'Übung {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Supersatz · direkt nacheinander, Pause erst danach', + 'Superset · do these back-to-back, rest when done': 'Supersatz · direkt nacheinander, Pause erst danach', 'Freestyle workout — add your first exercise.': 'Freies Training — füge deine erste Übung hinzu.', 'Finish workout early · {0} exercises': 'Training vorzeitig beenden · {0} Übungen', 'Rest over — next set!': 'Pause vorbei — nächster Satz!', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index b1fd37d..a80f623 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Las series registradas en esta sesión se perderán.', 'Superset {0} / {1}': 'Superserie {0} / {1}', 'Exercise {0} / {1}': 'Ejercicio {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Superserie · hazlos seguidos, descansa después de ambos', + 'Superset · do these back-to-back, rest when done': 'Superserie · hazlos seguidos, descansa al final', 'Freestyle workout — add your first exercise.': 'Entrenamiento libre — añade tu primer ejercicio.', 'Finish workout early · {0} exercises': 'Terminar antes · {0} ejercicios', 'Rest over — next set!': '¡Descanso terminado — siguiente serie!', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index e3d91d9..a9207b8 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Les séries notées dans cette session seront perdues.', 'Superset {0} / {1}': 'Superset {0} / {1}', 'Exercise {0} / {1}': 'Exercice {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Superset · enchaîne-les, repos après les deux', + 'Superset · do these back-to-back, rest when done': 'Superset · enchaîne-les, repos à la fin', 'Freestyle workout — add your first exercise.': 'Séance libre — ajoute ton premier exercice.', 'Finish workout early · {0} exercises': 'Terminer plus tôt · {0} exercices', 'Rest over — next set!': 'Repos fini — série suivante !', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 9e05cfe..60e2e2a 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'इस सत्र में दर्ज किए सेट खो जाएँगे।', 'Superset {0} / {1}': 'सुपरसेट {0} / {1}', 'Exercise {0} / {1}': 'व्यायाम {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'सुपरसेट · इन्हें लगातार करें, दोनों के बाद आराम', + 'Superset · do these back-to-back, rest when done': 'सुपरसेट · इन्हें लगातार करें, अंत में आराम', 'Freestyle workout — add your first exercise.': 'फ्रीस्टाइल वर्कआउट — पहला व्यायाम जोड़ें।', 'Finish workout early · {0} exercises': 'जल्दी समाप्त करें · {0} व्यायाम', 'Rest over — next set!': 'आराम खत्म — अगला सेट!', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index a4b21bd..a9f01db 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Le serie registrate in questa sessione andranno perse.', 'Superset {0} / {1}': 'Superset {0} / {1}', 'Exercise {0} / {1}': 'Esercizio {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Superset · falli uno dopo l’altro, riposo dopo entrambi', + 'Superset · do these back-to-back, rest when done': 'Superset · falli uno dopo l’altro, riposo alla fine', 'Freestyle workout — add your first exercise.': 'Allenamento libero — aggiungi il primo esercizio.', 'Finish workout early · {0} exercises': 'Termina in anticipo · {0} esercizi', 'Rest over — next set!': 'Riposo finito — prossima serie!', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index c309e6a..6a811fd 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': '이 세션에서 기록한 세트가 사라집니다.', 'Superset {0} / {1}': '슈퍼세트 {0} / {1}', 'Exercise {0} / {1}': '운동 {0} / {1}', - 'Superset · do these back-to-back, rest after both': '슈퍼세트 · 연달아 수행하고, 둘 다 끝난 뒤 휴식', + 'Superset · do these back-to-back, rest when done': '슈퍼세트 · 연달아 수행하고, 전부 끝난 뒤 휴식', 'Freestyle workout — add your first exercise.': '자유 운동 — 첫 운동을 추가하세요.', 'Finish workout early · {0} exercises': '일찍 마치기 · 운동 {0}개', 'Rest over — next set!': '휴식 끝 — 다음 세트!', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index 568d0dc..ddc2fa6 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Serie zapisane w tej sesji zostaną utracone.', 'Superset {0} / {1}': 'Superseria {0} / {1}', 'Exercise {0} / {1}': 'Ćwiczenie {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Superseria · rób jedno po drugim, odpocznij po obu', + 'Superset · do these back-to-back, rest when done': 'Superseria · rób jedno po drugim, odpocznij na końcu', 'Freestyle workout — add your first exercise.': 'Trening dowolny — dodaj pierwsze ćwiczenie.', 'Finish workout early · {0} exercises': 'Zakończ wcześniej · {0} ćwiczeń', 'Rest over — next set!': 'Koniec przerwy — następna seria!', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 006d63d..3e50cf5 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'As séries registadas nesta sessão vão perder-se.', 'Superset {0} / {1}': 'Supersérie {0} / {1}', 'Exercise {0} / {1}': 'Exercício {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Supersérie · faz seguidos, descansa depois de ambos', + 'Superset · do these back-to-back, rest when done': 'Supersérie · faz seguidos, descansa no final', 'Freestyle workout — add your first exercise.': 'Treino livre — adiciona o teu primeiro exercício.', 'Finish workout early · {0} exercises': 'Terminar mais cedo · {0} exercícios', 'Rest over — next set!': 'Descanso terminado — próxima série!', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index bb2a735..1dbc915 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Подходы, записанные в этой сессии, будут потеряны.', 'Superset {0} / {1}': 'Суперсет {0} / {1}', 'Exercise {0} / {1}': 'Упражнение {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Суперсет · выполняй подряд, отдых после обоих', + 'Superset · do these back-to-back, rest when done': 'Суперсет · выполняй подряд, отдых в конце', 'Freestyle workout — add your first exercise.': 'Свободная тренировка — добавь первое упражнение.', 'Finish workout early · {0} exercises': 'Завершить раньше · упражнений: {0}', 'Rest over — next set!': 'Отдых окончен — следующий подход!', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index d1a2147..b3c3879 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': 'Bu oturumda kaydettiğin setler kaybolacak.', 'Superset {0} / {1}': 'Süperset {0} / {1}', 'Exercise {0} / {1}': 'Egzersiz {0} / {1}', - 'Superset · do these back-to-back, rest after both': 'Süperset · art arda yap, ikisinden sonra dinlen', + 'Superset · do these back-to-back, rest when done': 'Süperset · art arda yap, sonunda dinlen', 'Freestyle workout — add your first exercise.': 'Serbest antrenman — ilk egzersizini ekle.', 'Finish workout early · {0} exercises': 'Erken bitir · {0} egzersiz', 'Rest over — next set!': 'Dinlenme bitti — sıradaki set!', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 37b6a72..0157fa2 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -162,7 +162,7 @@ export default { 'The sets you logged in this session will be lost.': '本次记录的组数将丢失。', 'Superset {0} / {1}': '超级组 {0} / {1}', 'Exercise {0} / {1}': '动作 {0} / {1}', - 'Superset · do these back-to-back, rest after both': '超级组 · 连续完成,两个都做完再休息', + 'Superset · do these back-to-back, rest when done': '超级组 · 连续完成,全部做完再休息', 'Freestyle workout — add your first exercise.': '自由训练——添加你的第一个动作。', 'Finish workout early · {0} exercises': '提前结束 · {0} 个动作', 'Rest over — next set!': '休息结束——下一组!', diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 28cc9e6..94d7be9 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -299,7 +299,7 @@ function ActiveWorkout() { {isSuperset ? (
- {t('Superset · do these back-to-back, rest after both')} + {t('Superset · do these back-to-back, rest when done')}
{unit.map((idx, k) =>
From d8c734a2b6fe7ab95a4fa8633dca21dc7624cce8 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 11 Aug 2026 22:30:04 +0200 Subject: [PATCH 34/58] muscle overlay: route the exercise detail tags through smOf too #67 stopped mutating EXDB and moved the secondary-muscle additions into a derived smOf() overlay, but ExerciseDetail still read the raw ex.sm. The four curated row additions (0027, 0293, 0499, 0861) were silently dropped from the detail sheet's tag row -- "rear deltoids" was the third visible tag on all four, so the slice(0,3) did not hide it. Caught on merge, before it shipped. --- frontend/src/sheets.jsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 180faa1..14d2720 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' -import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf } from './lib/exercises.js' +import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf } from './lib/exercises.js' import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.js' import { beep, vibrate } from './lib/sound.js' @@ -291,7 +291,7 @@ function ExerciseDetail({ ex, close }) { {t(ex.bp)} {ex.tg && {t(ex.tg)}} {t(ex.eq)} - {(ex.sm || []).slice(0, 3).map((s, i) => {t(s)})} + {smOf(ex).slice(0, 3).map((s, i) => {t(s)})}
{ex.desc &&
{ex.desc}
} {best > 0 &&
{t('Best:')} {fmtNum(best)} {st.unit}{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}
} From a7d7f5c24b1dadce126f399fea38da985f8b39cc Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 11 Aug 2026 22:35:43 +0200 Subject: [PATCH 35/58] Fix media paths on routine detail, map the Hevy names that fell through Two reported bugs, both small: exercise media (#79): IMG_BASE/GIF_BASE were relative, so on /plan/r/:id -- the app's only two-segment route -- the browser resolved them against the route and asked for /plan/r/img/..., which nginx's extension block 404s instead of falling through to index.html. Blank images, nothing in the console. Absolute defaults; the VITE_* overrides are absolute already, so the Pages demo and the mobile build are unaffected. import aliases (#74): Treadmill, Goblet Squat, Cycling and Cable Core Pallof Press arrived as custom exercises because no word-overlap can reach the catalogue's names for them. Added those plus the neighbours around them, and a test file -- matchExercise had none. Also documents that VITE_IMG_BASE/VITE_GIF_BASE are build-time, which is why setting them next to docker compose does nothing on a prebuilt image. --- docs/SELF_HOSTING.md | 11 ++++++ frontend/src/lib/exercises.js | 9 +++-- frontend/src/lib/import-csv.js | 11 ++++++ frontend/src/lib/import-match.test.js | 50 +++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 frontend/src/lib/import-match.test.js diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md index d130cfe..695317f 100644 --- a/docs/SELF_HOSTING.md +++ b/docs/SELF_HOSTING.md @@ -178,3 +178,14 @@ downloaded media are untouched. | Day reminder fires at the wrong time | Toggle it off and on in Settings so it re-detects your browser's timezone (also happens automatically on every app load — see section 6). | | Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. | | `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). | +| Exercise images/GIFs blank when a routine is open | Fixed in current images (issue #79). On an older build, see the note below. | + +### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time + +These two are read by Vite when the frontend is **compiled**, so their values are baked into +the shipped JavaScript bundle. Setting them in the `.env` next to `docker compose` has no +effect on an already-built image — the bundle has already made up its mind. + +They are only useful if you build the frontend yourself (`docker compose up -d --build`, or a +`npm run build` with the variables exported). If you need to redirect media on a prebuilt +image, do it in your reverse proxy instead. diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index f47cb88..27ec701 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -50,9 +50,14 @@ export const allExercises = st => [...(st.customEx || []), ...EXDB] // A build can point them somewhere else — the demo build pulls them off a CDN instead of // shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain // Node; the guard keeps this module loadable without Vite. +// The defaults are absolute on purpose (issue #79). A bare 'img/' resolves against the +// current document's directory, so on the one two-segment route in the app, /plan/r/:id, +// every request went to /plan/r/img/… and 404'd — and nginx's extension block has no +// try_files, so it 404s rather than falling through to index.html, leaving a blank image +// and nothing in the console. const ENV = import.meta.env || {} -const IMG_BASE = ENV.VITE_IMG_BASE || 'img/' -const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/' +const IMG_BASE = ENV.VITE_IMG_BASE || '/img/' +const GIF_BASE = ENV.VITE_GIF_BASE || '/gif/' export const imgSrc = ex => IMG_BASE + ex.img export const gifSrc = ex => GIF_BASE + ex.gif diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js index 125ca58..b09f984 100644 --- a/frontend/src/lib/import-csv.js +++ b/frontend/src/lib/import-csv.js @@ -173,6 +173,17 @@ const ALIAS_EX = { 'tricep pushdown': '0241', 'triceps pushdown': '0241', pushdown: '0241', skullcrusher: '0060', 'skull crusher': '0060', 'lying triceps extension': '0061', lunge: '0054', lunges: '0054', 'cable crossover': '1269', 'cable cross over': '1269', + 'goblet squat': '1760', 'dumbbell goblet squat': '1760', 'kettlebell goblet squat': '0534', + // Reported in issue #74: these come out of Hevy under names no word-overlap can reach, so + // they landed as custom exercises. The catalogue's cardio vocabulary is thin (29 of 1,324 + // entries), so each of these is the *only* candidate rather than the best of several. + treadmill: '3666', 'treadmill walk': '3666', 'treadmill run': '3666', + cycling: '2331', 'cross trainer': '2331', elliptical: '2141', + 'stationary bike': '2138', 'exercise bike': '2138', 'stepmill': '2311', + // The catalogue has only band Pallof presses, so a cable one resolves to the band entry: + // same movement, wrong equipment label, which beats leaving it uncategorised. + 'pallof press': '0979', 'cable pallof press': '0979', 'vertical pallof press': '1015', + 'cable core pallof press': '0979', 'core pallof press': '0979', } let ALIAS_IDX = null diff --git a/frontend/src/lib/import-match.test.js b/frontend/src/lib/import-match.test.js new file mode 100644 index 0000000..631b667 --- /dev/null +++ b/frontend/src/lib/import-match.test.js @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest' +import { matchExercise } from './import-csv.js' +import { EXIDX } from './exercises.js' + +// The names other apps actually export, and the catalogue entry each has to land on. +// Everything here was reported as arriving in the app as a *custom* exercise (issue #74): +// the alias table is the intended place to fix that, so these pin it. +const MAPS = { + Treadmill: '3666', + 'Goblet Squat': '1760', + Cycling: '2331', + 'Cable Core Pallof Press': '0979', + Elliptical: '2141', + 'Stationary Bike': '2138', +} + +describe('foreign exercise names resolve to the catalogue', () => { + for (const [name, id] of Object.entries(MAPS)) { + it(`maps "${name}" to ${id}`, () => { + expect(matchExercise(name)).toBe(id) + expect(EXIDX[id]).toBeTruthy() // an alias pointing at a dropped id is worse than no alias + }) + } + + // Equipment qualifiers must still beat the bare alias, or an import files years of + // dumbbell work under the barbell lift. + it('keeps the qualified variants distinct', () => { + expect(matchExercise('Kettlebell Goblet Squat')).toBe('0534') + expect(matchExercise('Dumbbell Goblet Squat')).toBe('1760') + }) + + // The word-bag is order-insensitive, which is what lets one alias cover the two ways + // exporters write the same movement. + it('ignores word order and case', () => { + expect(matchExercise('Squat (Barbell)')).toBe(matchExercise('Barbell Squat')) + }) + + // Regression guard for the aliases added above: the common lifts must not have moved. + it('leaves the established aliases alone', () => { + expect(matchExercise('Bench Press')).toBe('0025') + expect(matchExercise('Squat')).toBe('0043') + expect(matchExercise('Barbell Row')).toBe('0027') + expect(matchExercise('Deadlift')).toBe('0032') + }) + + it('still refuses to guess', () => { + expect(matchExercise('Some Movement I Invented')).toBe(null) + expect(matchExercise('')).toBe(null) + }) +}) From 528cb70a792b66789b43a804507fae1dd854c96d Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 11 Aug 2026 22:37:31 +0200 Subject: [PATCH 36/58] Changelog v1.2.6: Session-Supersets, Muscle-Map-Overlay, Medien-Pfade und Import-Aliase --- CHANGELOG.md | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5937601..124762c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,56 @@ account. Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in [#50](https://github.com/DuarteSantos8/openGym/pull/50). +### Pair exercises into a superset mid-session (#64) + +- 🔗 **"Make superset with previous / next" on each exercise card.** Two exercises paired in the + session collapse into a single *Superset* card — do them back-to-back, rest once at the end — + with an **Unpair** button in the header. No planning ahead required; pair them when you decide + to, in the workout. +- **Groups are any size.** Pairing the end of one group to the start of another merges them, and + the header wording stays correct past two exercises. +- **Unpairing cleans up after itself.** A group reduced to one exercise is dissolved rather than + left as a superset of one, and the pairing helpers never mutate the running session. +- Session-only by design: pairings drive the workout, and history stores the sets. + +Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in +[#64](https://github.com/DuarteSantos8/openGym/pull/64). + +### The muscle map stops rewriting the catalogue (#67) + +- **The curated secondary-muscle additions are now an overlay, not a mutation.** The four row + exercises that strain the rear delts used to get that written into the shared exercise dataset + at import time, which meant export, print and import saw a catalogue that had been edited + underneath them. They are derived at the read points instead, so the dataset stays pristine. +- The detail sheet's tag row reads through the same overlay, so those muscles still show where + they always did. + +Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in +[#67](https://github.com/DuarteSantos8/openGym/pull/67). + +### Fixes + +- 🖼️ **Exercise images and animations were blank on the routine screen** ([#79]). The media paths + were relative, and `/plan/r/:id` is the app's only two-segment route — so the browser asked for + `/plan/r/img/…` and got a 404 with nothing in the console to say why. Every other screen was + fine, which is what made it look like a one-screen mystery. Reported with the root cause already + found, by [@lemi1000](https://github.com/lemi1000). +- 📥 **Imports mapped more of what other apps export** ([#74]). Treadmill, Goblet Squat, Cycling and + Cable Core Pallof Press arrived as *custom* exercises rather than catalogue ones — no word + overlap could reach the names openGym stores them under. Those and their neighbours are now in + the alias table. Already-imported history stays custom; new imports resolve. Reported by + [@KiloOscarSix](https://github.com/KiloOscarSix). +- **A progression edge case that could loop forever** ([#60]). An entry left with nothing but + warm-up rows seeded the set-growth loop from a warm-up, which could never satisfy its own exit + condition. It leaves the entry alone instead. Contributed by + [@Space-Hermes](https://github.com/Space-Hermes). +- Documented that `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time values, so setting them next to + `docker compose` does nothing on a prebuilt image. + +[#79]: https://github.com/DuarteSantos8/openGym/issues/79 +[#74]: https://github.com/DuarteSantos8/openGym/issues/74 +[#60]: https://github.com/DuarteSantos8/openGym/pull/60 + ## v1.2.5 — 2026-08-04 Nothing in the app itself changed. This release adds an optional side door: a small server that From f32c4d0b73561848d9aa902ff7b02ce500ab2d85 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 11 Aug 2026 21:38:34 +0200 Subject: [PATCH 37/58] feat: remove exercise from a session (confirm; superset picker) --- frontend/src/views/Workout.jsx | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 94d7be9..f59ca7a 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -218,6 +218,43 @@ function ActiveWorkout() { const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null + // Remove a whole exercise from the session. The confirmation always asks first; in a + // superset it asks WHICH exercise of the group to remove. + const removeExercise = idx => update(s => { + if (!s.active || !Array.isArray(s.active.entries)) return + if (idx < 0 || idx >= s.active.entries.length) return + s.active.entries.splice(idx, 1) + if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1) + }, true) + const confirmRemoveExercise = idx => { + const e = A.entries[idx] + if (!e) return + const hasDone = (e.sets || []).some(s => s.done) + confirmSheet({ + title: t('Remove {0}?', exOr(e.id).n), + message: hasDone + ? t('The sets you logged for this exercise in this session will be lost.') + : t('This removes the exercise from your current session.'), + confirmText: t('Remove'), danger: true, onConfirm: () => removeExercise(idx) + }) + } + const removeExerciseSheet = () => { + if (unit.length > 1) { + useUI.getState().openSheet(close => ( +
+

{t('Remove exercise')}

+
{t('Which exercise in this superset do you want to remove?')}
+
+ {unit.map(idx =>
{ close(); confirmRemoveExercise(idx) }}> +
{exOr(A.entries[idx]?.id).n}
+ +
)} +
+
+ )) + } else confirmRemoveExercise(cur) + } + // A timed set is held, not typed. The work timer records what was actually held — an early // finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then // checks the set off through the normal path, so rest, supersets and the finish prompt all @@ -333,6 +370,10 @@ function ActiveWorkout() { s.active.cur = s.active.entries.length - 1 }), null, routine, seed) })} icon="plus">{t('Add exercise')} +
+
+ +
{(() => { const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length From b42d2baa6e829e0f8d231e213a3ddf516d3a0fc7 Mon Sep 17 00:00:00 2001 From: root Date: Tue, 11 Aug 2026 23:18:45 +0200 Subject: [PATCH 38/58] fix: make session exercise removal timer-safe --- frontend/package-lock.json | 99 ++++++++++++++++- frontend/package.json | 1 + frontend/src/locales/de.js | 5 + frontend/src/locales/es.js | 5 + frontend/src/locales/fr.js | 5 + frontend/src/locales/hi.js | 5 + frontend/src/locales/it.js | 5 + frontend/src/locales/ko.js | 5 + frontend/src/locales/pl.js | 5 + frontend/src/locales/pt.js | 5 + frontend/src/locales/ru.js | 5 + frontend/src/locales/tr.js | 5 + frontend/src/locales/zh.js | 5 + frontend/src/views/Workout.jsx | 34 +++--- frontend/src/views/Workout.remove.test.jsx | 117 +++++++++++++++++++++ 15 files changed, 292 insertions(+), 14 deletions(-) create mode 100644 frontend/src/views/Workout.remove.test.jsx diff --git a/frontend/package-lock.json b/frontend/package-lock.json index fbdf56d..57a6390 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/core": "^7.6.8", @@ -24,6 +24,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", + "happy-dom": "^20.11.2", "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" @@ -1265,6 +1266,23 @@ "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", "dev": true }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -2071,6 +2089,19 @@ "node": "*" } }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -3276,6 +3307,38 @@ "uglify-js": "^3.1.4" } }, + "node_modules/happy-dom": { + "version": "20.11.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz", + "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/happy-dom/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/hard-rejection": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", @@ -6418,6 +6481,16 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "dev": true }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", @@ -6494,6 +6567,28 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xcode": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index cca5e4f..943b428 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -28,6 +28,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", + "happy-dom": "^20.11.2", "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 779b301..49fc327 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -94,6 +94,11 @@ export default { 'Weight ({0})': 'Gewicht ({0})', 'Add to routine': 'Zur Routine hinzufügen', 'Remove exercise': 'Übung entfernen', + 'Remove {0}?': '{0} entfernen?', + 'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.', + 'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.', + 'Remove': 'Entfernen', + 'Which exercise in this superset do you want to remove?': 'Welche Übung in diesem Supersatz möchtest du entfernen?', 'Pick an icon': 'Symbol auswählen', // --- day planning / calendar --- 'Back to weekly plan': 'Zurück zum Wochenplan', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index a80f623..0606e9f 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Peso ({0})', 'Add to routine': 'Añadir a la rutina', 'Remove exercise': 'Quitar ejercicio', + 'Remove {0}?': '¿Quitar {0}?', + 'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.', + 'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.', + 'Remove': 'Quitar', + 'Which exercise in this superset do you want to remove?': '¿Qué ejercicio de esta superserie quieres quitar?', 'Pick an icon': 'Elige un icono', 'Back to weekly plan': 'Volver al plan semanal', '{0} set to rest': '{0} marcado como descanso', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index a9207b8..225fcd7 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Poids ({0})', 'Add to routine': 'Ajouter à la routine', 'Remove exercise': "Retirer l'exercice", + 'Remove {0}?': 'Retirer {0} ?', + 'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.', + 'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.', + 'Remove': 'Retirer', + 'Which exercise in this superset do you want to remove?': 'Quel exercice de ce superset veux-tu retirer ?', 'Pick an icon': 'Choisis une icône', 'Back to weekly plan': 'Retour au plan hebdo', '{0} set to rest': '{0} passé en repos', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 60e2e2a..2879ba4 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'वज़न ({0})', 'Add to routine': 'रूटीन में जोड़ें', 'Remove exercise': 'व्यायाम हटाएँ', + 'Remove {0}?': '{0} हटाएँ?', + 'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।', + 'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।', + 'Remove': 'हटाएँ', + 'Which exercise in this superset do you want to remove?': 'इस सुपरसेट से कौन-सा व्यायाम हटाना है?', 'Pick an icon': 'आइकन चुनें', 'Back to weekly plan': 'साप्ताहिक योजना पर वापस', '{0} set to rest': '{0} आराम के लिए सेट', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index a9f01db..bc91583 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Peso ({0})', 'Add to routine': 'Aggiungi alla routine', 'Remove exercise': 'Rimuovi esercizio', + 'Remove {0}?': 'Rimuovere {0}?', + 'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.', + 'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.', + 'Remove': 'Rimuovi', + 'Which exercise in this superset do you want to remove?': 'Quale esercizio di questa superserie vuoi rimuovere?', 'Pick an icon': 'Scegli un’icona', 'Back to weekly plan': 'Torna al piano settimanale', '{0} set to rest': '{0} impostato a riposo', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 6a811fd..67b668c 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': '무게 ({0})', 'Add to routine': '루틴에 추가', 'Remove exercise': '운동 제거', + 'Remove {0}?': '{0}을(를) 제거할까요?', + 'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.', + 'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.', + 'Remove': '제거', + 'Which exercise in this superset do you want to remove?': '이 슈퍼세트에서 어떤 운동을 제거할까요?', 'Pick an icon': '아이콘 선택', 'Back to weekly plan': '주간 계획으로 복귀', '{0} set to rest': '{0}을(를) 휴식일로 설정', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index ddc2fa6..5a9bee5 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Ciężar ({0})', 'Add to routine': 'Dodaj do planu', 'Remove exercise': 'Usuń ćwiczenie', + 'Remove {0}?': 'Usunąć {0}?', + 'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.', + 'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.', + 'Remove': 'Usuń', + 'Which exercise in this superset do you want to remove?': 'Które ćwiczenie z tej superserii chcesz usunąć?', 'Pick an icon': 'Wybierz ikonę', 'Back to weekly plan': 'Wróć do planu tygodnia', '{0} set to rest': '{0} ustawiono jako odpoczynek', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 3e50cf5..56b7331 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Peso ({0})', 'Add to routine': 'Adicionar à rotina', 'Remove exercise': 'Remover exercício', + 'Remove {0}?': 'Remover {0}?', + 'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.', + 'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.', + 'Remove': 'Remover', + 'Which exercise in this superset do you want to remove?': 'Que exercício desta supersérie queres remover?', 'Pick an icon': 'Escolhe um ícone', 'Back to weekly plan': 'Voltar ao plano semanal', '{0} set to rest': '{0} marcado como descanso', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 1dbc915..cce6de8 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Вес ({0})', 'Add to routine': 'Добавить в программу', 'Remove exercise': 'Убрать упражнение', + 'Remove {0}?': 'Удалить {0}?', + 'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.', + 'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.', + 'Remove': 'Удалить', + 'Which exercise in this superset do you want to remove?': 'Какое упражнение из этого суперсета удалить?', 'Pick an icon': 'Выбери иконку', 'Back to weekly plan': 'Вернуться к недельному плану', '{0} set to rest': '{0} — теперь день отдыха', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index b3c3879..89965d2 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': 'Ağırlık ({0})', 'Add to routine': 'Rutine ekle', 'Remove exercise': 'Egzersizi kaldır', + 'Remove {0}?': '{0} kaldırılsın mı?', + 'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.', + 'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.', + 'Remove': 'Kaldır', + 'Which exercise in this superset do you want to remove?': 'Bu süper sette hangi egzersizi kaldırmak istiyorsun?', 'Pick an icon': 'Bir simge seç', 'Back to weekly plan': 'Haftalık plana dön', '{0} set to rest': '{0} dinlenme olarak ayarlandı', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 0157fa2..2ae1793 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -90,6 +90,11 @@ export default { 'Weight ({0})': '重量({0})', 'Add to routine': '加入训练日', 'Remove exercise': '移除动作', + 'Remove {0}?': '移除 {0}?', + 'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。', + 'This removes the exercise from your current session.': '这会从当前训练中移除该动作。', + 'Remove': '移除', + 'Which exercise in this superset do you want to remove?': '你想移除这个超级组中的哪个动作?', 'Pick an icon': '选择图标', 'Back to weekly plan': '恢复每周计划', '{0} set to rest': '{0} 已设为休息', diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index f59ca7a..93ad588 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { exOr } from '../lib/exercises.js' -import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset } from '../lib/history.js' +import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } from '../lib/history.js' import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' @@ -169,11 +169,24 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov } /* ---------- active workout ---------- */ +export function removeActiveExercise(idx) { + // Clear the work callback before indexes can shift. This also protects a confirmation sheet + // that was opened first and confirmed after a timed hold started. + useUI.getState().stopWork() + useStore.getState().update(s => { + if (!s.active || !Array.isArray(s.active.entries)) return + if (idx < 0 || idx >= s.active.entries.length) return + s.active.entries.splice(idx, 1) + cleanupSg(s.active.entries) + if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1) + }, true) +} + function ActiveWorkout() { const nav = useNavigate() const S = useStore(s => s.S) const update = useStore(s => s.update) - const { startRest, stopRest } = useUI() + const { startRest, stopRest, work } = useUI() const A = S.active const units = supersetUnits(A.entries) const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1)) @@ -220,12 +233,7 @@ function ActiveWorkout() { // Remove a whole exercise from the session. The confirmation always asks first; in a // superset it asks WHICH exercise of the group to remove. - const removeExercise = idx => update(s => { - if (!s.active || !Array.isArray(s.active.entries)) return - if (idx < 0 || idx >= s.active.entries.length) return - s.active.entries.splice(idx, 1) - if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1) - }, true) + const removeExercise = removeActiveExercise const confirmRemoveExercise = idx => { const e = A.entries[idx] if (!e) return @@ -370,10 +378,12 @@ function ActiveWorkout() { s.active.cur = s.active.entries.length - 1 }), null, routine, seed) })} icon="plus">{t('Add exercise')} -
-
- -
+ {A.entries.length > 0 && <> +
+
+ +
+ }
{(() => { const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length diff --git a/frontend/src/views/Workout.remove.test.jsx b/frontend/src/views/Workout.remove.test.jsx new file mode 100644 index 0000000..f1c2d0a --- /dev/null +++ b/frontend/src/views/Workout.remove.test.jsx @@ -0,0 +1,117 @@ +// @vitest-environment happy-dom +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { MemoryRouter } from 'react-router-dom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Workout, { removeActiveExercise } from './Workout.jsx' +import { DEF, useStore } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' + +vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() })) +vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) })) + +globalThis.IS_REACT_ACT_ENVIRONMENT = true +const clone = value => JSON.parse(JSON.stringify(value)) +const entry = (id, sg) => ({ + id, + ...(sg ? { sg } : {}), + target: { sets: 1, reps: 1 }, + sets: [{ w: 0, r: 1, done: false }] +}) + +let root +let container + +function setActive(entries) { + const S = clone(DEF) + S.active = { + id: 'remove-test', d: '2026-08-11', start: Date.now(), routineId: null, + name: 'Remove test', bw: null, cur: 0, entries + } + useStore.setState({ S, user: null }) +} + +function renderWorkout(entries) { + setActive(entries) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + act(() => root.render()) +} + +function removeButton() { + return [...container.querySelectorAll('button')].find(button => button.textContent.includes('Remove exercise')) +} + +beforeEach(() => { + vi.useFakeTimers() + localStorage.clear() + useUI.getState().stopRest() + useUI.getState().stopWork() + useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null }) + useStore.setState({ S: clone(DEF), user: null }) + root = null + container = null +}) + +afterEach(() => { + if (root) act(() => root.unmount()) + if (container) container.remove() + useUI.getState().stopRest() + useUI.getState().stopWork() + vi.clearAllTimers() + vi.useRealTimers() +}) + +describe('active-session exercise removal', () => { + it('disables removal for the whole duration of a timed hold', () => { + renderWorkout([entry('1001')]) + expect(removeButton()).toBeTruthy() + expect(removeButton().disabled).toBe(false) + + act(() => useUI.getState().startWork(30, 'Hold', vi.fn())) + + expect(removeButton().disabled).toBe(true) + }) + + it('cancels a pending timed callback before indexes shift and cleans a one-member group', () => { + setActive([entry('1001', 'sg-1'), entry('1002', 'sg-1'), entry('1003')]) + const wrongWrite = vi.fn(elapsed => { + useStore.getState().update(s => { s.active.entries[0].sets[0].sec = elapsed }) + }) + useUI.getState().startWork(5, 'Hold', wrongWrite) + + removeActiveExercise(0) + vi.advanceTimersByTime(10_000) + + const active = useStore.getState().S.active + expect(useUI.getState().work).toBeNull() + expect(wrongWrite).not.toHaveBeenCalled() + expect(active.entries.map(e => e.id)).toEqual(['1002', '1003']) + expect(active.entries[0].sg).toBeUndefined() + expect(active.entries[0].sets[0].sec).toBeUndefined() + }) + + it('hides the remove control for an empty freestyle session', () => { + renderWorkout([]) + expect(removeButton()).toBeUndefined() + }) +}) + +describe('remove-exercise locale coverage', () => { + const required = [ + 'Remove {0}?', + 'The sets you logged for this exercise in this session will be lost.', + 'This removes the exercise from your current session.', + 'Remove', + 'Which exercise in this superset do you want to remove?' + ] + const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' }) + + it('defines every new prompt in all eleven locale packs', () => { + expect(Object.keys(packs)).toHaveLength(11) + Object.entries(packs).forEach(([path, pack]) => { + required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key)) + }) + }) +}) From 237d1c5cf2653657696618b3ada349d9b9bee8d0 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 17:20:04 +0200 Subject: [PATCH 39/58] fix: decrement cur when the removed entry sits below it (superset picker case) --- frontend/src/views/Workout.jsx | 1 + frontend/src/views/Workout.remove.test.jsx | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 93ad588..1e7242c 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -178,6 +178,7 @@ export function removeActiveExercise(idx) { if (idx < 0 || idx >= s.active.entries.length) return s.active.entries.splice(idx, 1) cleanupSg(s.active.entries) + if (idx < s.active.cur) s.active.cur-- if (s.active.cur >= s.active.entries.length) s.active.cur = Math.max(0, s.active.entries.length - 1) }, true) } diff --git a/frontend/src/views/Workout.remove.test.jsx b/frontend/src/views/Workout.remove.test.jsx index f1c2d0a..1243c39 100644 --- a/frontend/src/views/Workout.remove.test.jsx +++ b/frontend/src/views/Workout.remove.test.jsx @@ -22,11 +22,11 @@ const entry = (id, sg) => ({ let root let container -function setActive(entries) { +function setActive(entries, cur = 0) { const S = clone(DEF) S.active = { id: 'remove-test', d: '2026-08-11', start: Date.now(), routineId: null, - name: 'Remove test', bw: null, cur: 0, entries + name: 'Remove test', bw: null, cur, entries } useStore.setState({ S, user: null }) } @@ -75,7 +75,8 @@ describe('active-session exercise removal', () => { }) it('cancels a pending timed callback before indexes shift and cleans a one-member group', () => { - setActive([entry('1001', 'sg-1'), entry('1002', 'sg-1'), entry('1003')]) + setActive([entry('1001', 'sg-1'), entry('1002', 'sg-1'), entry('1003')], 1) + expect(useStore.getState().S.active.cur).toBe(1) const wrongWrite = vi.fn(elapsed => { useStore.getState().update(s => { s.active.entries[0].sets[0].sec = elapsed }) }) @@ -88,6 +89,7 @@ describe('active-session exercise removal', () => { expect(useUI.getState().work).toBeNull() expect(wrongWrite).not.toHaveBeenCalled() expect(active.entries.map(e => e.id)).toEqual(['1002', '1003']) + expect(active.cur).toBe(0) expect(active.entries[0].sg).toBeUndefined() expect(active.entries[0].sets[0].sec).toBeUndefined() }) From edde72f9cba3108a0fd9aa07c1fc6b4ec48ea456 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 17:20:50 +0200 Subject: [PATCH 40/58] fix: superset flow round-3 (rest gate for ordinary exercises, high-water progress, top-weight owns advance, Workout coverage) --- frontend/src/lib/supersetFlow.js | 28 +++++ frontend/src/lib/supersetFlow.test.js | 36 +++++++ frontend/src/views/Workout.jsx | 57 ++++++++-- frontend/src/views/Workout.test.jsx | 146 ++++++++++++++++++++++++++ 4 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 frontend/src/lib/supersetFlow.js create mode 100644 frontend/src/lib/supersetFlow.test.js create mode 100644 frontend/src/views/Workout.test.jsx diff --git a/frontend/src/lib/supersetFlow.js b/frontend/src/lib/supersetFlow.js new file mode 100644 index 0000000..c78e72c --- /dev/null +++ b/frontend/src/lib/supersetFlow.js @@ -0,0 +1,28 @@ +// Pure decisions for the active-workout superset flow. Keeping these independent of React and +// the stores makes the uneven-round and re-check rules explicit and directly testable. +const hasWork = (entries, idx) => !!entries[idx]?.sets?.some(set => !set.done) + +// A completion is new progress only when it takes this exercise beyond the largest number of +// simultaneously completed sets seen in this mounted session. Uncheck/re-check therefore does +// not repeat navigation or rest side effects, while completing an added set still can. +export function setProgressHighWater(entry, previous = 0) { + const done = entry?.sets?.reduce((count, set) => count + (set.done ? 1 : 0), 0) || 0 + return { isNew: done > previous, highWater: Math.max(previous, done) } +} + +// Decide where a newly completed superset set goes next. Spent members are skipped, including +// across the wrap. A round ends when no later member in display order has work left; this makes +// the last *active* member the boundary rather than blindly using the group's last array index. +export function supersetFlowStep(entries, unit, fromIdx) { + if (!Array.isArray(entries) || !Array.isArray(unit) || unit.length <= 1) return null + const pos = unit.indexOf(fromIdx) + if (pos < 0) return null + + const unitDone = !unit.some(idx => hasWork(entries, idx)) + if (unitDone) return { unitDone: true, roundDone: false, nextIdx: null } + + const wrapped = [...unit.slice(pos + 1), ...unit.slice(0, pos + 1)] + const nextIdx = wrapped.find(idx => hasWork(entries, idx)) ?? null + const roundDone = !unit.slice(pos + 1).some(idx => hasWork(entries, idx)) + return { unitDone: false, roundDone, nextIdx } +} diff --git a/frontend/src/lib/supersetFlow.test.js b/frontend/src/lib/supersetFlow.test.js new file mode 100644 index 0000000..2c96a16 --- /dev/null +++ b/frontend/src/lib/supersetFlow.test.js @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { setProgressHighWater, supersetFlowStep } from './supersetFlow.js' + +const entry = done => ({ sets: done.map(value => ({ done: value })) }) + +describe('supersetFlowStep', () => { + it('does not create navigation or rest flow for a normal singleton exercise', () => { + const entries = [entry([true]), entry([false])] + expect(supersetFlowStep(entries, [0], 0)).toBeNull() + }) + + it('does not count an uncheck/re-check of previously completed work as new progress', () => { + const finished = entry([true, true, true]) + expect(setProgressHighWater(finished, 3)).toEqual({ isNew: false, highWater: 3 }) + expect(setProgressHighWater(finished, 2)).toEqual({ isNew: true, highWater: 3 }) + }) + + it('skips a spent short member and uses the last member with work as the round boundary', () => { + // A has just completed set two of three; B's only set was completed last round. + const entries = [entry([true, true, false]), entry([true])] + expect(supersetFlowStep(entries, [0, 1], 0)).toEqual({ + unitDone: false, + roundDone: true, + nextIdx: 0 + }) + }) + + it('wraps to the next member with work at a normal round boundary', () => { + const entries = [entry([true, false, false]), entry([true])] + expect(supersetFlowStep(entries, [0, 1], 1)).toEqual({ + unitDone: false, + roundDone: true, + nextIdx: 0 + }) + }) +}) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 94d7be9..0fcfeb7 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' @@ -8,6 +8,7 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { t } from '../lib/i18n.js' import { api } from '../lib/api.js' +import { setProgressHighWater, supersetFlowStep } from '../lib/supersetFlow.js' import Media from '../components/Media.jsx' import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -180,6 +181,15 @@ function ActiveWorkout() { const unit = A.entries.length ? unitOf(units, cur) : [] const unitIdx = units.findIndex(u => u === unit) const isSuperset = unit.length > 1 + // Superset flow: keep the active exercise in view - completing a set scrolls to the + // next exercise in the group, then back up to the first exercise of the next round. + const exRefs = useRef({}) + const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length)) + useEffect(() => { + if (!isSuperset) return + const el = exRefs.current[cur] + if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) + }, [cur, isSuperset, A.entries.length]) const total = A.entries.reduce((n, e) => n + e.sets.length, 0) const done = setsDoneActive(A) @@ -234,15 +244,13 @@ function ActiveWorkout() { const m = modeAt(idx) const cardioEntry = m === 'cardio' const isLastUnit = unitIdx >= units.length - 1 - let askTop = false, exJustDone = false, workoutDone = false + let askTop = false, exJustDone = false, workoutDone = false, checked = false mutEntry(idx, e => { e.sets[i].done = !e.sets[i].done + checked = e.sets[i].done if (e.sets[i].done) { beep(S.sound, 1040, 0.12); vibrate(30) - const isLastExInUnit = idx === unit[unit.length - 1] const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done)) - if (isLastExInUnit && !unitDone) startRest(S.restSec) - else if (unitDone) stopRest() if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done // Only loaded reps training has a "working weight" worth confirming — a bodyweight // plank has nothing to put in that slider, and neither does a set of push-ups @@ -257,6 +265,43 @@ function ActiveWorkout() { else if (workoutDone) workoutCompleteSheet() else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged')) else if (exJustDone && m === 'time') useUI.getState().toast(t('Hold logged')) + + // Only progress beyond this exercise's high-water mark may navigate or change rest. This + // prevents an uncheck/re-check of finished work from replaying the flow side effects. + const fresh = useStore.getState().S.active + if (fresh && checked && fresh.entries[idx]) { + const progress = setProgressHighWater(fresh.entries[idx], progressHighWater.current[idx] || 0) + progressHighWater.current[idx] = progress.highWater + if (!progress.isNew) return + + const freshUnits = supersetUnits(fresh.entries) + const freshUnit = freshUnits.find(u => u.includes(idx)) + const freshUnitIdx = freshUnits.indexOf(freshUnit) + const freshLastUnit = freshUnitIdx >= freshUnits.length - 1 + const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done)) + + // Singleton units are ordinary exercises: preserve their historical between-set rest, + // while final sets finish quietly and never enter superset navigation. + if (freshUnitDone) stopRest() + if (!freshUnit || freshUnit.length <= 1) { + if (!freshUnitDone) startRest(S.restSec) + return + } + + const step = supersetFlowStep(fresh.entries, freshUnit, idx) + if (!step) return + if (step.unitDone) { + if (!freshLastUnit) { + const nextUnit = freshUnits[freshUnitIdx + 1] + // The top-weight sheet's explicit "Just close" path owns the choice not to advance. + if (!askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] }) + startRest(S.restSec) + } + } else { + if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx }) + if (step.roundDone) startRest(S.restSec) + } + } } // Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only — @@ -302,7 +347,7 @@ function ActiveWorkout() { {t('Superset · do these back-to-back, rest when done')}
- {unit.map((idx, k) =>
+ {unit.map((idx, k) =>
{ exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}> {k > 0 &&
+
} toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} /> diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx new file mode 100644 index 0000000..9794b7e --- /dev/null +++ b/frontend/src/views/Workout.test.jsx @@ -0,0 +1,146 @@ +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { parseHTML } from 'linkedom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Workout from './Workout.jsx' + +const mocks = vi.hoisted(() => { + const state = { + S: null, + startRest: vi.fn(), + stopRest: vi.fn(), + topWeightSheet: vi.fn(), + } + state.storeSnapshot = () => ({ + S: state.S, + user: null, + update: mut => mut(state.S), + }) + state.uiSnapshot = () => ({ + work: null, + startRest: state.startRest, + stopRest: state.stopRest, + startWork: vi.fn(), + toast: vi.fn(), + }) + return state +}) + +vi.mock('../store/useStore.js', () => { + const useStore = selector => selector(mocks.storeSnapshot()) + useStore.getState = mocks.storeSnapshot + return { useStore } +}) +vi.mock('../store/useUI.js', () => { + const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot() + useUI.getState = mocks.uiSnapshot + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ + startFlow: vi.fn(), + exercisePicker: vi.fn(), + exConfigSheet: vi.fn(), + exerciseDetailSheet: vi.fn(), + topWeightSheet: mocks.topWeightSheet, + finishWorkout: vi.fn(), + workoutCompleteSheet: vi.fn(), + confirmSheet: vi.fn(), +})) +vi.mock('../components/Media.jsx', () => ({ default: () => null })) + +let dom +let root +let container + +function exercise(id, sets, extra = {}) { + return { + id, + target: { mode: 'reps', reps: 5, weight: 60, bodyweight: false }, + sets: sets.map(done => ({ w: 60, r: 5, done })), + ...extra, + } +} + +function workout(entries, cur = 0) { + return { + unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full', + workouts: [], exWeights: {}, routines: [], + active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries }, + } +} + +function installDom() { + const parsed = parseHTML('
') + dom = parsed.window + globalThis.window = dom + globalThis.document = dom.document + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator }) + for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key] + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.getElementById('root') + root = createRoot(container) +} + +async function mount(entries, cur = 0) { + mocks.S = workout(entries, cur) + installDom() + await act(async () => { root.render(React.createElement(Workout)) }) +} + +async function unmount() { + if (!root) return + await act(async () => { root.unmount() }) + root = null + container = null + dom = null +} + +async function toggleSet(index) { + const checkbox = container.querySelectorAll('[role="checkbox"]')[index] + expect(checkbox).toBeTruthy() + await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) }) +} + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(async () => { + await unmount() +}) + +describe('Workout set completion flow', () => { + it('starts rest after a non-final ordinary set, but stops rest without restarting it on the final set', async () => { + await mount([exercise('plain-bench', [false, false, false])]) + await toggleSet(0) + + expect(mocks.startRest).toHaveBeenCalledOnce() + expect(mocks.startRest).toHaveBeenCalledWith(90) + expect(mocks.stopRest).not.toHaveBeenCalled() + + await unmount() + vi.clearAllMocks() + await mount([exercise('plain-treadmill', [false], { + target: { mode: 'cardio', min: 20, speed: 8 }, + })]) + await toggleSet(0) + + expect(mocks.stopRest).toHaveBeenCalledOnce() + expect(mocks.startRest).not.toHaveBeenCalled() + }) + + it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => { + const group = 'superset-1' + await mount([ + exercise('superset-a', [true, true, true], { sg: group, asked: true }), + exercise('superset-b', [true, true, false], { sg: group }), + exercise('next-exercise', [false, false, false]), + ], 1) + await toggleSet(5) + + expect(mocks.topWeightSheet).toHaveBeenCalledWith(1) + expect(mocks.S.active.cur).toBe(1) + expect(mocks.startRest).toHaveBeenCalledWith(90) + }) +}) From a95104b67519af8ca063ab34c7dec3a293a8d741 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 17:25:27 +0200 Subject: [PATCH 41/58] fix: back-button history accounting (explicit pushed-entry counter, locked-sheet popstate) + mouse-drag slider opt-out --- frontend/src/components/Modals.jsx | 89 ++++++++++- frontend/src/components/Modals.test.jsx | 201 ++++++++++++++++++++++++ 2 files changed, 288 insertions(+), 2 deletions(-) create mode 100644 frontend/src/components/Modals.test.jsx diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsx index 0923ee8..0e0083b 100644 --- a/frontend/src/components/Modals.jsx +++ b/frontend/src/components/Modals.jsx @@ -35,13 +35,38 @@ function Sheet({ sheet }) { else el.style.transform = '' d.startY = null } + // Mouse drag (desktop testing / trackpads): same swipe-to-dismiss behaviour. + const onMouseDown = e => { + if (e.button !== 0) return + if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) { + drag.current = { startY: null, delta: 0 } + return + } + const el = ref.current + drag.current = { startY: el.scrollTop <= 0 ? e.clientY : null, delta: 0 } + } + const onMouseMove = e => { + const el = ref.current, d = drag.current + if (d.startY === null) return + d.delta = e.clientY - d.startY + if (d.delta > 0 && el.scrollTop <= 0) { + e.preventDefault() + el.style.transition = 'none' + el.style.transform = `translateY(${d.delta}px)` + } else d.delta = 0 + } + const onMouseUp = () => onTouchEnd() // non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref) useEffect(() => { const el = ref.current if (!el) return el.addEventListener('touchmove', onTouchMove, { passive: false }) - return () => el.removeEventListener('touchmove', onTouchMove) + window.addEventListener('mouseup', onMouseUp) + return () => { + el.removeEventListener('touchmove', onTouchMove) + window.removeEventListener('mouseup', onMouseUp) + } }, []) const close = () => closeSheet(sheet.id) @@ -56,7 +81,8 @@ function Sheet({ sheet }) { return (
{ if (!sheet.locked) close() }} /> -
+
{sheet.render(close)}
@@ -66,8 +92,67 @@ function Sheet({ sheet }) { export default function Modals() { const sheets = useUI(s => s.sheets) + const closeSheet = useUI(s => s.closeSheet) + const prevLen = useRef(0) + const suppressPop = useRef(false) + const pushedEntries = useRef(0) + const sheetEntries = useRef([]) + + // Every opened sheet gets a history entry so Android back dismisses it instead of + // leaving the page (issue #63). Keep the pushed-entry count and each active sheet's + // live-entry status explicit: sheet count cannot tell whether popstate already spent + // an entry (especially for a locked sheet) or whether several sheets opened at once. + useEffect(() => { + const prev = prevLen.current + prevLen.current = sheets.length + if (sheets.length > prev) { + for (let i = prev; i < sheets.length; i++) { + sheetEntries.current.push({ openedAt: location.href, live: true }) + history.pushState({ openGymSheet: true }, '') + pushedEntries.current++ + } + } else if (sheets.length < prev) { + const closedEntries = sheetEntries.current.splice(sheets.length, prev - sheets.length) + const rewind = closedEntries.filter(entry => + entry.live && !(typeof entry.openedAt === 'string' && location.href !== entry.openedAt)).length + if (rewind > 0) { + pushedEntries.current = Math.max(0, pushedEntries.current - rewind) + suppressPop.current = true + history.go(-rewind) + } + // Entries skipped because the app moved on remain in pushedEntries as deliberate + // leaks until a later popstate consumes them with no corresponding active sheet. + } + }, [sheets.length]) + + useEffect(() => { + const onPop = () => { + if (suppressPop.current) { suppressPop.current = false; return } + if (pushedEntries.current <= 0) return + pushedEntries.current-- + // The browser has already spent one pushed entry. Mark the latest live active + // sheet entry spent even when the sheet is locked; with no active entry this is a + // moved-on leak, which is still accounted for by the counter decrement above. + for (let i = sheetEntries.current.length - 1; i >= 0; i--) { + if (sheetEntries.current[i].live) { + sheetEntries.current[i].live = false + break + } + } + const top = sheets[sheets.length - 1] + if (top && !top.locked) closeSheet(top.id) + } + window.addEventListener('popstate', onPop) + return () => window.removeEventListener('popstate', onPop) + }, [sheets, closeSheet]) // lock the page behind any open sheet (iOS-safe) + useEffect(() => { + if (!sheets.length) return + const onKey = e => { if (e.key === 'Escape') { const top = useUI.getState().sheets[useUI.getState().sheets.length - 1]; if (top && !top.locked) useUI.getState().closeSheet(top.id) } } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [sheets.length]) useEffect(() => { if (!sheets.length) return const y = window.scrollY || 0 diff --git a/frontend/src/components/Modals.test.jsx b/frontend/src/components/Modals.test.jsx new file mode 100644 index 0000000..79fa383 --- /dev/null +++ b/frontend/src/components/Modals.test.jsx @@ -0,0 +1,201 @@ +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { parseHTML } from 'linkedom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Modals from './Modals.jsx' + +const mocks = vi.hoisted(() => { + const listeners = new Set() + const state = { + sheets: [], + closeSheet(id) { + state.sheets = state.sheets.filter(sheet => sheet.id !== id) + listeners.forEach(listener => listener()) + }, + } + return { + state, + subscribe(listener) { + listeners.add(listener) + return () => listeners.delete(listener) + }, + setSheets(sheets) { + state.sheets = sheets + listeners.forEach(listener => listener()) + }, + } +}) + +vi.mock('../store/useUI.js', async () => { + const React = await import('react') + const useUI = (selector = state => state) => React.useSyncExternalStore( + mocks.subscribe, + () => selector(mocks.state), + () => selector(mocks.state), + ) + useUI.getState = () => mocks.state + return { useUI } +}) + +let dom +let root +let container +let historyMock +let locationMock + +function sheet(id, { locked = false, render = () => React.createElement('div') } = {}) { + return { id, locked, kind: 'sheet', render } +} + +function installDom() { + const parsed = parseHTML('
') + dom = parsed.window + dom.scrollTo = vi.fn() + globalThis.window = dom + globalThis.document = dom.document + Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator }) + for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key] + globalThis.IS_REACT_ACT_ENVIRONMENT = true + + locationMock = { href: 'https://opengym.test/#/workout' } + historyMock = { pushState: vi.fn(), go: vi.fn() } + Object.defineProperty(globalThis, 'location', { configurable: true, value: locationMock }) + Object.defineProperty(globalThis, 'history', { configurable: true, value: historyMock }) + + container = document.getElementById('root') + root = createRoot(container) +} + +async function setSheets(sheets) { + await act(async () => { mocks.setSheets(sheets) }) +} + +async function popstate() { + await act(async () => { window.dispatchEvent(new dom.Event('popstate')) }) +} + +function mouse(target, type, clientY) { + const event = new dom.Event(type, { bubbles: true }) + Object.defineProperties(event, { + button: { value: 0 }, + clientY: { value: clientY }, + }) + target.dispatchEvent(event) +} + +beforeEach(async () => { + mocks.state.sheets = [] + installDom() + await act(async () => { root.render(React.createElement(Modals)) }) +}) + +afterEach(async () => { + if (root) await act(async () => { root.unmount() }) + root = null + container = null + dom = null + vi.restoreAllMocks() +}) + +describe('Modals sheet history accounting', () => { + it('does not rewind a real page after back spends a locked FinishSummary entry', async () => { + const confirm = sheet('confirm') + const summary = sheet('summary', { locked: true }) + + await setSheets([confirm]) + expect(historyMock.pushState).toHaveBeenCalledTimes(1) + + // ConfirmDialog closes and FinishSummary opens in the same batch: length remains one, + // so the existing pushed entry now belongs to the locked summary. + await setSheets([summary]) + await popstate() + expect(mocks.state.sheets).toEqual([summary]) + + await act(async () => { mocks.state.closeSheet('summary') }) + expect(historyMock.go).not.toHaveBeenCalled() + }) + + it('pushes and rewinds the exact number of entries for batched sheets', async () => { + await setSheets([sheet('one'), sheet('two')]) + expect(historyMock.pushState).toHaveBeenCalledTimes(2) + + await setSheets([]) + expect(historyMock.go).toHaveBeenCalledTimes(1) + expect(historyMock.go).toHaveBeenCalledWith(-2) + }) + + it('closes stacked sheets one entry at a time on back', async () => { + await setSheets([sheet('one'), sheet('two')]) + await popstate() + + expect(mocks.state.sheets.map(item => item.id)).toEqual(['one']) + expect(historyMock.pushState).toHaveBeenCalledTimes(2) + + await popstate() + expect(mocks.state.sheets).toEqual([]) + expect(historyMock.go).not.toHaveBeenCalled() + }) + + it('closes an unlocked sheet on back without rewinding its already-spent entry', async () => { + await setSheets([sheet('open')]) + await popstate() + + expect(mocks.state.sheets).toEqual([]) + expect(historyMock.go).not.toHaveBeenCalled() + }) + + it('accounts for a moved-on entry even when popstate has no current sheet', async () => { + await setSheets([sheet('navigating')]) + locationMock.href = 'https://opengym.test/#/home' + await setSheets([]) + expect(historyMock.go).not.toHaveBeenCalled() + + // This spends the deliberately leaked entry with top === undefined. + await popstate() + + const locked = sheet('locked', { locked: true }) + await setSheets([locked]) + await popstate() + await setSheets([]) + expect(historyMock.go).not.toHaveBeenCalled() + }) +}) + +describe('Modals mouse dragging', () => { + it('leaves range sliders opted out of sheet dragging', async () => { + await setSheets([sheet('slider', { + render: () => React.createElement('input', { type: 'range' }), + })]) + const sheetEl = container.querySelector('.sheet') + const slider = container.querySelector('input[type="range"]') + sheetEl.scrollTop = 0 + + await act(async () => { + mouse(slider, 'mousedown', 10) + mouse(sheetEl, 'mousemove', 150) + window.dispatchEvent(new dom.Event('mouseup')) + }) + + expect(sheetEl.style.transform).toBe('') + expect(mocks.state.sheets).toHaveLength(1) + }) + + it('releases a drag when mouseup occurs outside the sheet', async () => { + await setSheets([sheet('drag')]) + const sheetEl = container.querySelector('.sheet') + sheetEl.scrollTop = 0 + + await act(async () => { + mouse(sheetEl, 'mousedown', 10) + mouse(sheetEl, 'mousemove', 60) + }) + expect(sheetEl.style.transform).toBe('translateY(50px)') + + await act(async () => { window.dispatchEvent(new dom.Event('mouseup')) }) + expect(sheetEl.style.transform).toBe('') + + await act(async () => { mouse(sheetEl, 'mousemove', 120) }) + expect(sheetEl.style.transform).toBe('') + expect(mocks.state.sheets).toHaveLength(1) + }) +}) From ed666df2377569b6603973cf2a2261d41e1a0428 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 17:25:57 +0200 Subject: [PATCH 42/58] fix: fatigue round-4 (zero-load strength, history-stable reference, real Stats view tests + committed probe) --- frontend/package-lock.json | 388 +++++-------------- frontend/package.json | 5 +- frontend/scripts/fatigue-monotonic-probe.mjs | 100 +++++ frontend/src/lib/recovery.js | 242 ++++++++++-- frontend/src/lib/recovery.test.js | 291 +++++++++++++- frontend/src/views/Stats.jsx | 16 +- frontend/src/views/Stats.recovery.test.jsx | 172 ++++---- 7 files changed, 759 insertions(+), 455 deletions(-) create mode 100644 frontend/scripts/fatigue-monotonic-probe.mjs diff --git a/frontend/package-lock.json b/frontend/package-lock.json index fbdf56d..d923859 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengym-frontend", - "version": "1.2.5", + "version": "1.2.6", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/core": "^7.6.8", @@ -24,7 +24,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", - "linkedom": "^0.18.13", + "happy-dom": "^20.11.2", "vite": "^8.1.5", "vitest": "^4.1.10" } @@ -1265,6 +1265,23 @@ "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", "dev": true }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -2071,6 +2088,19 @@ "node": "*" } }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -2595,13 +2625,6 @@ "url": "https://github.com/sponsors/fb55" } }, - "node_modules/cssom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", - "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", - "dev": true, - "license": "MIT" - }, "node_modules/dargs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", @@ -3276,6 +3299,38 @@ "uglify-js": "^3.1.4" } }, + "node_modules/happy-dom": { + "version": "20.11.2", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz", + "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/happy-dom/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/hard-rejection": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/hard-rejection/-/hard-rejection-2.1.0.tgz", @@ -3345,105 +3400,6 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, - "node_modules/html-escaper": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", - "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/htmlparser2": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", - "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", - "dev": true, - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.2.2", - "entities": "^7.0.1" - } - }, - "node_modules/htmlparser2/node_modules/dom-serializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "entities": "^4.2.0" - }, - "funding": { - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/domhandler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "domelementtype": "^2.3.0" - }, - "engines": { - "node": ">= 4" - }, - "funding": { - "url": "https://github.com/fb55/domhandler?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/domutils": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", - "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "dom-serializer": "^2.0.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3" - }, - "funding": { - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/htmlparser2/node_modules/entities": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", - "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -3933,181 +3889,6 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, - "node_modules/linkedom": { - "version": "0.18.13", - "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz", - "integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==", - "dev": true, - "license": "ISC", - "dependencies": { - "css-select": "^7.0.0", - "cssom": "^0.5.0", - "html-escaper": "^3.0.3", - "htmlparser2": "^10.1.0", - "uhyphen": "^0.2.0" - }, - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "canvas": ">= 2" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/linkedom/node_modules/boolbase": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz", - "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/css-select": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz", - "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^2.0.0", - "css-what": "^8.0.0", - "domhandler": "^6.0.1", - "domutils": "^4.0.2", - "nth-check": "^3.0.1" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/css-what": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz", - "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/linkedom/node_modules/dom-serializer": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", - "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^3.0.0", - "domhandler": "^6.0.0", - "entities": "^8.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/domelementtype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz", - "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/linkedom/node_modules/domhandler": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz", - "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "domelementtype": "^3.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/domhandler?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/domutils": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz", - "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "dom-serializer": "^3.0.0", - "domelementtype": "^3.0.0", - "domhandler": "^6.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/entities": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", - "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/linkedom/node_modules/nth-check": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz", - "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^2.0.0" - }, - "engines": { - "node": ">=20.19.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/fb55/nth-check?sponsor=1" - } - }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", @@ -6168,13 +5949,6 @@ "node": ">=0.8.0" } }, - "node_modules/uhyphen": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz", - "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==", - "dev": true, - "license": "ISC" - }, "node_modules/undici-types": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", @@ -6418,6 +6192,16 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", "dev": true }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", @@ -6494,6 +6278,28 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "dev": true }, + "node_modules/ws": { + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xcode": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index cca5e4f..adb365e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,8 @@ "build:mobile": "VITE_MOBILE=1 VITE_IMG_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/images/ VITE_GIF_BASE=https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd/videos/ vite build && cap sync", "preview": "vite preview", "test": "vitest run", - "test:watch": "vitest" + "test:watch": "vitest", + "test:fatigue-probe": "node scripts/fatigue-monotonic-probe.mjs" }, "license": "AGPL-3.0-or-later", "dependencies": { @@ -28,7 +29,7 @@ "@capacitor/cli": "^7.6.8", "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", - "linkedom": "^0.18.13", + "happy-dom": "^20.11.2", "vite": "^8.1.5", "vitest": "^4.1.10" } diff --git a/frontend/scripts/fatigue-monotonic-probe.mjs b/frontend/scripts/fatigue-monotonic-probe.mjs new file mode 100644 index 0000000..89aec62 --- /dev/null +++ b/frontend/scripts/fatigue-monotonic-probe.mjs @@ -0,0 +1,100 @@ +import { FATIGUE_SCAN_MS, fatigueOf } from '../src/lib/recovery.js' + +const HOUR = 60 * 60 * 1000 +const DAY = 24 * HOUR +const BASE = Date.UTC(2026, 0, 31, 12) +const ID = '1254' + +const workout = (start, weight, count = 8) => ({ + d: new Date(start).toISOString(), + start, + entries: [{ + id: ID, + sets: Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })), + }], +}) + +// Deterministic LCG: failures reproduce exactly without an external property-testing dependency. +let seed = 0x5eed1234 +const random = () => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 + return seed / 0x100000000 +} + +let comparisons = 0 +let deletionComparisons = 0 +let largestIncrease = -Infinity +for (let historyIndex = 0; historyIndex < 100; historyIndex += 1) { + const sessionCount = 3 + Math.floor(random() * 10) + const history = Array.from({ length: sessionCount }, () => { + const ageHours = Math.floor(random() * 120 * 24) + const weight = 40 + Math.floor(random() * 141) + const count = 1 + Math.floor(random() * 12) + return workout(BASE - ageHours * HOUR, weight, count) + }) + + let previous = fatigueOf(history, BASE).chest + for (let hour = 1; hour <= 1080; hour += 1) { + const current = fatigueOf(history, BASE + hour * HOUR).chest + const increase = current - previous + largestIncrease = Math.max(largestIncrease, increase) + if (increase > 1e-12) { + throw new Error( + `fatigue increased in history ${historyIndex} at hour ${hour}: ${previous} -> ${current}`, + ) + } + previous = current + comparisons += 1 + } + + const beforeDeletion = fatigueOf(history, BASE) + for (let deleted = 0; deleted < history.length; deleted += 1) { + const afterDeletion = fatigueOf(history.filter((_, index) => index !== deleted), BASE) + for (const [slug, before] of Object.entries(beforeDeletion)) { + if (afterDeletion[slug] > before + Number.EPSILON) { + throw new Error( + `deleting workout ${deleted} in history ${historyIndex} increased ${slug}: ` + + `${before} -> ${afterDeletion[slug]}`, + ) + } + deletionComparisons += 1 + } + } +} + +if (comparisons !== 108000) throw new Error(`expected 108000 comparisons, got ${comparisons}`) + +// Pin the two history-edit invariants alongside the randomized property probes. +const today = workout(BASE, 100, 5) +const baseline = fatigueOf([today], BASE).chest +for (const oldImport of [workout(BASE - 90 * DAY, 140, 10), workout(BASE - 90 * DAY, 100, 20)]) { + if (fatigueOf([oldImport, today], BASE).chest !== baseline) { + throw new Error('an import older than the scan changed current fatigue') + } +} + +const deletionHistory = [ + workout(BASE - FATIGUE_SCAN_MS - DAY, 100, 15), + workout(BASE - 3 * DAY, 100, 8), + workout(BASE - 2 * DAY, 100, 8), + workout(BASE - DAY, 60, 4), + workout(BASE, 120, 10), +] +const beforePinnedDeletion = fatigueOf(deletionHistory, BASE) +for (let deleted = 0; deleted < deletionHistory.length; deleted += 1) { + const afterDeletion = fatigueOf( + deletionHistory.filter((_, index) => index !== deleted), + BASE, + ) + for (const [slug, before] of Object.entries(beforePinnedDeletion)) { + if (afterDeletion[slug] > before + Number.EPSILON) { + throw new Error(`deleting workout ${deleted} increased ${slug}: ${before} -> ${afterDeletion[slug]}`) + } + } +} + +console.log(`monotonic probe: ${comparisons} comparisons, largest increase ${largestIncrease}, PASS`) +console.log( + `history-edit probe: out-of-scan imports stable; ${deletionComparisons} randomized ` + + 'single-workout deletion comparisons non-increasing, PASS', +) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index ebc8020..d73b345 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -1,14 +1,20 @@ import { EXIDX } from './exercises.js' import { MUSCLES, musclesOf } from './muscles.js' -/** Completed-workout window used when calculating current fatigue. */ // A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve // 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting // fatigue level without ever pinning it, and the value can then fade asymptotically. -export const FATIGUE_REF_VOLUME = 3 +export const FATIGUE_REF_VOLUME = 2000 // default reference: kg of intensity-weighted volume per session +export const FATIGUE_MIN_SESSIONS = 3 // smoothing horizon for the causal per-muscle reference // Computational bound for the stimulus scan, not a semantic cliff: after 30 days (20 // half-lives) a session contributes below 1e-6 to the accumulated value. export const FATIGUE_SCAN_MS = 30 * 24 * 60 * 60 * 1000 +export const BODYWEIGHT_REF_LOAD = 75 // kg assumed for bodyweight exercises when no load is logged +export const CARDIO_TONNAGE_PER_MIN = 50 // duration proxy for cardio/timed work + +// Preserve the shipped set-count signal when a completed custom/imported exercise has no load. +// Two such sets therefore retain the old 1 - exp(-2 / 3) starting-fatigue reading. +const ZERO_LOAD_SET_STIMULUS = FATIGUE_REF_VOLUME / 3 /** Exponential half-life for fatigue stimulus. */ export const FATIGUE_HALF_LIFE_MS = 129600000 @@ -54,31 +60,184 @@ function emptyMuscleMap(value) { return Object.fromEntries(MUSCLES.map(slug => [slug, value])) } -function clamp(value, min, max) { - return Math.min(max, Math.max(min, value)) +// Epley one-rep-max estimate, matching onerm.js (REP_CAP included so high-rep sets do not +// inflate the estimate). Used only to express a set's intensity relative to the lifter's own +// capacity - the same formula the app already shows for estimated 1RM. +const REP_CAP = 12 +const epley1RM = (load, reps) => load * (1 + Math.min(reps || 1, REP_CAP) / 30) + +const LB_TO_KG = 0.45359237 + +function numeric(value) { + if (value === null || value === undefined || value === '' || typeof value === 'boolean') return null + const n = Number(value) + return Number.isFinite(n) ? n : null } -// Yield one weighted stimulus per completed set. Repeating the exercise's muscle weights for -// every done set is equivalent to multiplying musclesOf(ex) by the completed-set count while -// preserving the workout/set shape already used by the app. -function completedStimuli(workouts, include) { - const stimuli = [] - for (const workout of workouts || []) { - const timestamp = workoutTimestamp(workout) - if (!Number.isFinite(timestamp) || !include(timestamp)) continue - for (const entry of workout.entries || []) { - const weights = musclesOf(EXIDX[entry.id]) - for (const set of entry.sets || []) { - if (set?.done !== true) continue - for (const [slug, weight] of Object.entries(weights)) { - if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) { - stimuli.push({ slug, timestamp, stimulus: weight }) - } - } +function isPounds(unit) { + return /^(?:lb|lbs|pound|pounds)$/i.test(String(unit ?? '').trim()) +} + +function unitOf(...records) { + for (const record of records) { + if (!record || typeof record !== 'object') continue + for (const key of ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit']) { + if (record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== '') return record[key] + } + } + return 'kg' +} + +function kgOf(value, unit) { + const n = numeric(value) + if (n === null) return 0 + return Math.max(0, n) * (isPounds(unit) ? LB_TO_KG : 1) +} + +// A bodyweight value stamped on a workout is the best historical value. When old records do not +// carry one, use the current profile's canonical bodyweight supplied by Stats, then the stable +// fallback used by the original fatigue model. `bodyweightKg` is already canonical; `bodyweight` +// is accepted for callers that provide a display-unit value explicitly. +function bodyweightKgFor(workout, opts = {}, stampedLoadUnit) { + const stamped = numeric(workout?.bw) ?? numeric(workout?.bodyweight) + if (stamped !== null) { + return kgOf(stamped, unitOf( + { unit: workout?.bwUnit }, + { unit: workout?.bodyweightUnit }, + workout, + stampedLoadUnit && { unit: stampedLoadUnit }, + opts, + )) + } + const canonical = numeric(opts.bodyweightKg) + if (canonical !== null) return Math.max(0, canonical) + const display = numeric(opts.bodyweight) + if (display !== null) return kgOf(display, opts.bodyweightUnit || opts.unit || opts.profileUnit) + return BODYWEIGHT_REF_LOAD +} + +function bodyweightTarget(entry) { + const target = entry?.target + if (target && Object.prototype.hasOwnProperty.call(target, 'bodyweight')) return !!target.bodyweight + if (entry && Object.prototype.hasOwnProperty.call(entry, 'bodyweight')) return !!entry.bodyweight + return null +} + +function hasUnitStamp(...records) { + return records.some(record => record && typeof record === 'object' + && ['unit', 'u', 'weightUnit', 'weight_unit', 'loadUnit'].some(key => Object.prototype.hasOwnProperty.call(record, key) + && record[key] !== undefined && record[key] !== null && String(record[key]).trim() !== '')) +} + +function bodyweightConfigured(ex, entry, set, workout, opts = {}) { + const configured = bodyweightTarget(entry) + if (configured !== null) return configured + // Before target.bodyweight was persisted, a positive `w` on a catalogue bodyweight exercise + // already meant an explicitly entered load. Keep those rows compatible when no body-mass + // context is available; a stamped workout or a profile bodyweight makes the intended total-load + // semantics unambiguous even for old entries. + const added = kgOf(set?.w, unitOf(set, entry?.target, entry, workout, opts)) + const hasBodyweightContext = numeric(workout?.bw) !== null + || numeric(workout?.bodyweight) !== null + || Object.prototype.hasOwnProperty.call(opts, 'bodyweightKg') + || numeric(opts.bodyweight) !== null + || hasUnitStamp(set, entry?.target, entry, workout) + return ex?.eq === 'body weight' && (added === 0 || hasBodyweightContext) +} + +function loadKgFor(ex, entry, set, workout, opts = {}) { + const setUnit = unitOf(set, entry?.target, entry, workout, opts) + const addedKg = kgOf(set?.w, setUnit) + const loadUnit = hasUnitStamp(set, entry?.target, entry) ? setUnit : undefined + return bodyweightConfigured(ex, entry, set, workout, opts) + ? bodyweightKgFor(workout, opts, loadUnit) + addedKg + : addedKg +} + +// Best Epley estimate inside one session. Keeping intensity context on the session makes a +// scored stimulus independent of later imports/deletes; unlike an all-history maximum, a +// 90-day-old CSV row cannot retroactively reweight today's sets. +function session1RMs(workout, opts = {}) { + const best = new Map() + for (const entry of workout?.entries || []) { + const ex = EXIDX[entry.id] + for (const set of entry.sets || []) { + const load = loadKgFor(ex, entry, set, workout, opts) + if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue + const est = epley1RM(load, set.r) + if (!best.has(entry.id) || est > best.get(entry.id)) best.set(entry.id, est) + } + } + return best +} + +// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5. +// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its +// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no +// 1RM history stay unweighted (duration proxies, or intensity 1 for the first sessions). +function setTonnage(ex, entry, set, workout, oneRm, opts = {}) { + if (ex?.bp === 'cardio') { + return Math.max(set?.min || 0, (set?.sec || 0) / 60) * CARDIO_TONNAGE_PER_MIN + } + if (set?.sec != null && set?.r == null) { + return (set.sec / 60) * CARDIO_TONNAGE_PER_MIN + } + const reps = set?.r || 1 + const load = loadKgFor(ex, entry, set, workout, opts) + const raw = load * reps + // A bodyweight target is already an external-load-normalised total (body mass + any added + // load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so + // retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink + // a weighted bodyweight set below the unloaded version. + if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + if (!(oneRm > 0) || !(load > 0)) return raw + return raw * Math.min(1, load / oneRm) ** 1.5 +} + +// One session's per-muscle stimulus, calculated only from that session. A completed zero-load +// set gets the set-equivalent fallback instead of disappearing from fatigue. +function sessionTonnages(workout, opts = {}) { + const sums = emptyMuscleMap(0) + const oneRms = session1RMs(workout, opts) + for (const entry of workout?.entries || []) { + const weights = musclesOf(EXIDX[entry.id]) + for (const set of entry.sets || []) { + if (set?.done !== true) continue + const measured = setTonnage(EXIDX[entry.id], entry, set, workout, oneRms.get(entry.id), opts) + const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS + for (const [slug, weight] of Object.entries(weights)) { + if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight } } } - return stimuli + return sums +} + +// Build normalised stimuli in workout order. The reference seen by a session is strictly the +// reference left by earlier in-window sessions; the session cannot dilute its own score. The +// downward-only EWMA is deliberate: removing any earlier workout can only raise a later +// denominator (and removes its own positive stimulus), so deletion can never increase fatigue. +// Rebuilding from the bounded scan also makes imports older than the scan exactly irrelevant. +function fatigueStimuli(workouts, current, opts = {}) { + const cutoff = current - FATIGUE_SCAN_MS + const ordered = (workouts || []) + .map((workout, index) => ({ workout, index, timestamp: workoutTimestamp(workout) })) + .filter(item => Number.isFinite(item.timestamp) && item.timestamp > cutoff) + .sort((a, b) => a.timestamp - b.timestamp || a.index - b.index) + const references = emptyMuscleMap(FATIGUE_REF_VOLUME) + const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []])) + + for (const { workout, timestamp } of ordered) { + const sums = sessionTonnages(workout, opts) + for (const slug of MUSCLES) { + const stimulus = sums[slug] + if (!(stimulus > 0)) continue + byMuscle[slug].push({ slug, timestamp, stimulus: stimulus / references[slug] }) + const ewma = references[slug] + (stimulus - references[slug]) / FATIGUE_MIN_SESSIONS + references[slug] = Math.min(references[slug], ewma) + } + } + return byMuscle } const MUSCLES_BY_SLUG = Object.fromEntries(MUSCLES.map(slug => [slug, true])) @@ -97,7 +256,7 @@ function fatigueValue(events, now) { value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts // higher but never pins, and the value fades asymptotically - no window-edge cliff. - return 1 - Math.exp(-value / FATIGUE_REF_VOLUME) + return 1 - Math.exp(-value) } /** @@ -106,22 +265,21 @@ function fatigueValue(events, now) { * Stimulus time is `workout.start`, falling back to the workout date `workout.d`. Each completed * set contributes the exercise's `musclesOf` weights; the scan is bounded to FATIGUE_SCAN_MS for * performance, not semantics. Stimuli are accumulated chronologically with a 36-hour half-life, - * decayed to `now`, and normalised with the saturation curve 1 - exp(-v / FATIGUE_REF_VOLUME). + * decayed to `now`, and normalised with the saturation curve 1 - exp(-v). Each session is scored + * against a causal, downward-only EWMA left by strictly earlier in-window sessions. Session-local + * intensity estimates and the causal reference make out-of-window imports irrelevant, while + * deleting a workout can only remove stimulus and/or raise later references. * The result always contains every drawable muscle slug. * * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. * @param {number} now Current time in milliseconds; injected to keep this function deterministic. * @returns {Record} Fatigue values keyed by every drawable muscle slug. */ -export function fatigueOf(workouts, now) { +export function fatigueOf(workouts, now, opts = {}) { const current = Number(now) - const cutoff = current - FATIGUE_SCAN_MS - const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff) - const byMuscle = Object.fromEntries(MUSCLES.map(slug => [slug, []])) - for (const stimulus of stimuli) byMuscle[stimulus.slug].push(stimulus) - const result = emptyMuscleMap(0) if (!Number.isFinite(current)) return result + const byMuscle = fatigueStimuli(workouts, current, opts) for (const slug of MUSCLES) result[slug] = fatigueValue(byMuscle[slug], current) return result } @@ -138,12 +296,20 @@ export function fatigueOf(workouts, now) { * @param {number} now Current time in milliseconds; injected to keep this function deterministic. * @returns {Record} Retained-strength values keyed by every drawable muscle slug. */ -export function strengthOf(workouts, now) { +export function strengthOf(workouts, now, opts = {}) { const current = Number(now) const latest = Object.fromEntries(MUSCLES.map(slug => [slug, -Infinity])) - const stimuli = completedStimuli(workouts, () => true) - for (const stimulus of stimuli) { - if (stimulus.timestamp > latest[stimulus.slug]) latest[stimulus.slug] = stimulus.timestamp + for (const workout of workouts || []) { + const timestamp = workoutTimestamp(workout) + if (!Number.isFinite(timestamp)) continue + for (const entry of workout.entries || []) { + if (!(entry.sets || []).some(set => set?.done === true && !set?.warmup)) continue + for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) { + if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) { + latest[slug] = timestamp + } + } + } } const result = emptyMuscleMap(STRENGTH_FLOOR) @@ -174,8 +340,8 @@ export function strengthOf(workouts, now) { * @example * const avoid = fatiguedMuscles(workouts, now) */ -export function fatiguedMuscles(workouts, now) { - return Object.entries(fatigueOf(workouts, now)) +export function fatiguedMuscles(workouts, now, opts = {}) { + return Object.entries(fatigueOf(workouts, now, opts)) .filter(([, value]) => value > 0.5) .map(([slug]) => slug) } @@ -190,8 +356,8 @@ export function fatiguedMuscles(workouts, now) { * @example * const targets = detrainedMuscles(workouts, now) */ -export function detrainedMuscles(workouts, now) { - return Object.entries(strengthOf(workouts, now)) +export function detrainedMuscles(workouts, now, opts = {}) { + return Object.entries(strengthOf(workouts, now, opts)) .filter(([, value]) => value < 1) .map(([slug]) => slug) } diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js index 0f0d35a..11c1bee 100644 --- a/frontend/src/lib/recovery.test.js +++ b/frontend/src/lib/recovery.test.js @@ -1,9 +1,12 @@ import { describe, expect, it } from 'vitest' import { FATIGUE_HALF_LIFE_MS, + FATIGUE_MIN_SESSIONS, FATIGUE_REF_VOLUME, FATIGUE_SCAN_MS, FATIGUE_STATES, + BODYWEIGHT_REF_LOAD, + CARDIO_TONNAGE_PER_MIN, STRENGTH_FLOOR, STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, @@ -13,7 +16,7 @@ import { halfLifeDecay, strengthOf, } from './recovery.js' -import { EXDB } from './exercises.js' +import { EXDB, registerCustom } from './exercises.js' import { MUSCLES, musclesOf } from './muscles.js' import { fatigueStateOf } from './recovery-view.js' @@ -44,19 +47,37 @@ const workoutAt = (id, start, sets = [{ done: true }]) => ({ start, entries: [{ id, sets: sets.map(set => ({ ...set })) }], }) +const V = 640 * (30 / 38) ** 1.5 // intensity-weighted tonnage of one 80x8 fixture set (its own Epley estimate implies intensity 30/38) + const doneWorkoutAt = (id, start, count = 1) => - workoutAt(id, start, Array.from({ length: count }, () => ({ done: true }))) + workoutAt(id, start, Array.from({ length: count }, () => ({ done: true, w: 80, r: 8 }))) const zeroFatigue = () => Object.fromEntries(MUSCLES.map(slug => [slug, 0])) const floorStrength = () => Object.fromEntries(MUSCLES.map(slug => [slug, STRENGTH_FLOOR])) // Numeric fatigue remains the math API; the UI boundary selector is imported from production. const stableFloat = value => Number(value.toFixed(12)) +const referenceAfter = (reference, stimulus) => Math.min( + reference, + reference + (stimulus - reference) / FATIGUE_MIN_SESSIONS, +) + +const expectedFatigue = sessions => { + let reference = FATIGUE_REF_VOLUME + let normalised = 0 + for (const { stimulus, age = 0 } of sessions) { + normalised += stimulus / reference * halfLifeDecay(age, FATIGUE_HALF_LIFE_MS) + reference = referenceAfter(reference, stimulus) + } + return 1 - Math.exp(-normalised) +} describe('recovery constants', () => { it('exports the pinned windows, half-lives, floor, and state labels', () => { - expect(FATIGUE_REF_VOLUME).toBe(3) + expect(FATIGUE_REF_VOLUME).toBe(2000) expect(FATIGUE_SCAN_MS).toBe(30 * DAY) expect(FATIGUE_HALF_LIFE_MS).toBe(36 * HOUR) + expect(BODYWEIGHT_REF_LOAD).toBe(75) + expect(CARDIO_TONNAGE_PER_MIN).toBe(50) expect(STRENGTH_FULL_MS).toBe(14 * DAY) expect(STRENGTH_HALF_LIFE_MS).toBe(28 * DAY) expect(STRENGTH_FLOOR).toBe(0.5) @@ -88,24 +109,36 @@ describe('fatigueOf and strengthOf', () => { for (const slug of MUSCLES) { const weight = WEIGHTED_WEIGHTS[slug] || 0 - expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight / FATIGUE_REF_VOLUME), 10) + expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-V * weight / FATIGUE_REF_VOLUME), 10) expect(strength[slug]).toBe(weight ? 1 : STRENGTH_FLOOR) } - // one set never crosses the fatigued threshold on the saturating curve + // one set (80 x 8) never crosses the fatigued threshold on the saturating curve expect(fatiguedMuscles(workouts, NOW)).toEqual([]) + + // pure volume: one high-rep set at medium weight registers real tonnage (weighted by + // its intensity - its own Epley estimate with the 12-rep cap is 50 x 40/30 = 70 kg) + const highRep = [doneWorkoutAt(SINGLE.id, NOW, 1)] + highRep[0].entries[0].sets[0].w = 50 + highRep[0].entries[0].sets[0].r = 50 + const weighted = 2500 * (50 / (50 * (1 + 12 / 30))) ** 1.5 + expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeCloseTo( + 1 - Math.exp(-weighted / FATIGUE_REF_VOLUME), + 10, + ) + expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5) }) it('raises starting fatigue with volume, never pins, and fades without a cliff', () => { const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG] - expect(at0(1)).toBeCloseTo(1 - Math.exp(-1 / FATIGUE_REF_VOLUME), 10) - expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 / FATIGUE_REF_VOLUME), 10) - expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 / FATIGUE_REF_VOLUME), 10) + expect(at0(1)).toBeCloseTo(1 - Math.exp(-V / FATIGUE_REF_VOLUME), 10) + expect(at0(5)).toBeCloseTo(1 - Math.exp(-5 * V / FATIGUE_REF_VOLUME), 10) + expect(at0(12)).toBeCloseTo(1 - Math.exp(-12 * V / FATIGUE_REF_VOLUME), 10) expect(at0(12)).toBeGreaterThan(at0(5)) expect(at0(5)).toBeGreaterThan(at0(1)) expect(at0(12)).toBeLessThan(1) // one half-life later the gradient is still visible at any volume const later = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS, 12)], NOW)[SINGLE_SLUG] - expect(later).toBeCloseTo(1 - Math.exp(-6 / FATIGUE_REF_VOLUME), 10) + expect(later).toBeCloseTo(1 - Math.exp(-6 * V / FATIGUE_REF_VOLUME), 10) expect(later).toBeLessThan(at0(12)) // no cliff: 72h keeps decaying instead of snapping to zero const old = fatigueOf([doneWorkoutAt(SINGLE.id, NOW - 72 * HOUR)], NOW)[SINGLE_SLUG] @@ -118,13 +151,22 @@ describe('fatigueOf and strengthOf', () => { const fatigue = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age)], NOW) const expectedDecay = 0.5 ** (age / FATIGUE_HALF_LIFE_MS) for (const [slug, weight] of Object.entries(WEIGHTED_WEIGHTS)) { - expect(fatigue[slug]).toBeCloseTo(1 - Math.exp(-weight * expectedDecay / FATIGUE_REF_VOLUME), 10) + expect(fatigue[slug]).toBeCloseTo( + 1 - Math.exp(-V * weight * expectedDecay / FATIGUE_REF_VOLUME), + 10, + ) } if (age === FATIGUE_HALF_LIFE_MS) { - expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-0.5 / FATIGUE_REF_VOLUME), 10) + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo( + 1 - Math.exp(-V * 0.5 / FATIGUE_REF_VOLUME), + 10, + ) } if (age === FATIGUE_HALF_LIFE_MS / 2) { - expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(1 - Math.exp(-(0.5 ** 0.5) / FATIGUE_REF_VOLUME), 10) + expect(fatigue[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo( + 1 - Math.exp(-V * (0.5 ** 0.5) / FATIGUE_REF_VOLUME), + 10, + ) } } }) @@ -153,9 +195,9 @@ describe('fatigue state boundaries', () => { it('classifies exactly .25 as recovering and .2499 as ready', () => { const weight = WEIGHTED_WEIGHTS[SECONDARY_SLUG] - const sets = 3 + const sets = 4 const valueAt = target => { - const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * weight / rawAt(target)) + const age = FATIGUE_HALF_LIFE_MS * Math.log2(sets * V * weight / rawAt(target)) const value = fatigueOf([doneWorkoutAt(WEIGHTED.id, NOW - age, sets)], NOW)[SECONDARY_SLUG] expect(value).toBeCloseTo(target, 10) return stableFloat(value) @@ -166,10 +208,18 @@ describe('fatigue state boundaries', () => { }) it('classifies exactly .5 as recovering, .5001 as fatigued, and hooks only fatigued muscles', () => { - const sets = 3 - const atHalf = [doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.4999)), sets)] + const sets = 4 + const atHalf = [doneWorkoutAt( + SINGLE.id, + NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.4999)), + sets, + )] const aboveHalf = [ - doneWorkoutAt(SINGLE.id, NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets / rawAt(0.5001)), sets), + doneWorkoutAt( + SINGLE.id, + NOW - FATIGUE_HALF_LIFE_MS * Math.log2(sets * V / rawAt(0.5001)), + sets, + ), ] const half = fatigueOf(atHalf, NOW)[SINGLE_SLUG] const above = fatigueOf(aboveHalf, NOW)[SINGLE_SLUG] @@ -183,6 +233,92 @@ describe('fatigue state boundaries', () => { }) }) + +describe('causal fatigue reference', () => { + const loadedWorkout = (start, weight, count = 8) => workoutAt( + '1254', + start, + Array.from({ length: count }, () => ({ done: true, w: weight, r: 8 })), + ) + + it('scores each session against only the reference left by strictly earlier sessions', () => { + const old = doneWorkoutAt(SINGLE.id, NOW - DAY) + const today = doneWorkoutAt(SINGLE.id, NOW) + const earlierReference = referenceAfter(FATIGUE_REF_VOLUME, V) + const expected = 1 - Math.exp(-( + V / FATIGUE_REF_VOLUME * halfLifeDecay(DAY, FATIGUE_HALF_LIFE_MS) + + V / earlierReference + )) + + expect(fatigueOf([old, today], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) + expect(fatigueOf([today], NOW)[SINGLE_SLUG]).toBeCloseTo( + 1 - Math.exp(-V / FATIGUE_REF_VOLUME), + 10, + ) + }) + + it('keeps the 8x100x8 ten-day reproduction non-increasing as sessions leave the scan', () => { + const base = Date.UTC(2026, 0, 31, 12) + const workouts = [-20, -10, 0].map(days => loadedWorkout(base + days * DAY, 100)) + const observed = Array.from( + { length: 31 * 24 + 1 }, + (_, hour) => fatigueOf(workouts, base + hour * HOUR).chest, + ) + + expect(observed[0]).toBeGreaterThan(0.5) + expect(observed.at(-1)).toBe(0) + for (let index = 1; index < observed.length; index += 1) { + expect(observed[index]).toBeLessThanOrEqual(observed[index - 1] + Number.EPSILON) + } + }) + + it('ignores imports older than the scan, including their heavier 1RM data', () => { + const today = loadedWorkout(NOW, 100, 5) + const baseline = fatigueOf([today], NOW).chest + const heavyImport = loadedWorkout(NOW - 90 * DAY, 140, 10) + const highVolumeImport = loadedWorkout(NOW - 90 * DAY, 100, 20) + + expect(fatigueOf([heavyImport, today], NOW).chest).toBe(baseline) + expect(fatigueOf([highVolumeImport, today], NOW).chest).toBe(baseline) + }) + + it('never increases fatigue when any one workout is deleted', () => { + const workouts = [ + loadedWorkout(NOW - 40 * DAY, 100, 15), + loadedWorkout(NOW - 3 * DAY, 100, 8), + loadedWorkout(NOW - 2 * DAY, 100, 8), + loadedWorkout(NOW - DAY, 60, 4), + loadedWorkout(NOW, 120, 10), + ] + const before = fatigueOf(workouts, NOW) + + workouts.forEach((_, deletedIndex) => { + const after = fatigueOf(workouts.filter((__, index) => index !== deletedIndex), NOW) + for (const slug of MUSCLES) expect(after[slug]).toBeLessThanOrEqual(before[slug] + Number.EPSILON) + }) + }) + + it('rates a lighter current week below repeating the established load', () => { + const prior = [-21, -14, -7].map(days => loadedWorkout(NOW + days * DAY, 100)) + const lighter = fatigueOf([...prior, loadedWorkout(NOW, 50)], NOW).chest + const repeated = fatigueOf([...prior, loadedWorkout(NOW, 100)], NOW).chest + + expect(lighter).toBeLessThan(repeated) + }) + + it('uses the last registered bodyweight for bodyweight exercises', () => { + const bwEx = EXDB.find(ex => ex.eq === 'body weight' && ex.bp !== 'cardio') + if (!bwEx) throw new Error('test requires a bodyweight exercise fixture') + const slug = Object.keys(musclesOf(bwEx))[0] + const workout = { d: new Date(NOW).toISOString(), start: NOW, entries: [{ id: bwEx.id, sets: [{ done: true, r: 10 }] }] } + const at80 = fatigueOf([workout], NOW, { bodyweightKg: 80 })[slug] + const at90 = fatigueOf([workout], NOW, { bodyweightKg: 90 })[slug] + expect(at80).toBeCloseTo(1 - Math.exp(-800 / FATIGUE_REF_VOLUME), 10) + expect(at90).toBeCloseTo(1 - Math.exp(-900 / FATIGUE_REF_VOLUME), 10) + expect(at90).toBeGreaterThan(at80) + }) +}) + describe('strengthOf', () => { const strengthAt = age => strengthOf([doneWorkoutAt(SINGLE.id, NOW - age)], NOW)[SINGLE_SLUG] @@ -210,10 +346,15 @@ describe('accumulation and purity', () => { const ages = [64 * HOUR, 40 * HOUR] const workouts = ages.map(age => doneWorkoutAt(SINGLE.id, NOW - age)) const raw = ages.reduce( - (sum, age) => sum + 0.5 ** (age / FATIGUE_HALF_LIFE_MS), + (sum, age) => sum + V * 0.5 ** (age / FATIGUE_HALF_LIFE_MS), 0, ) - const expected = 1 - Math.exp(-raw / FATIGUE_REF_VOLUME) + const firstAge = ages[0] + const secondAge = ages[1] + const expected = expectedFatigue([ + { stimulus: V, age: firstAge }, + { stimulus: V, age: secondAge }, + ]) expect(raw).toBeLessThan(FATIGUE_REF_VOLUME) expect(fatigueOf(workouts, NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 10) @@ -222,7 +363,10 @@ describe('accumulation and purity', () => { it('saturates without pinning and returns identical results without mutating inputs or sharing state', () => { const saturated = [doneWorkoutAt(SINGLE.id, NOW, 2)] - expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo(1 - Math.exp(-2 / FATIGUE_REF_VOLUME), 10) + expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeCloseTo( + 1 - Math.exp(-2 * V / FATIGUE_REF_VOLUME), + 10, + ) expect(fatigueOf(saturated, NOW)[SINGLE_SLUG]).toBeLessThan(1) const workouts = [ @@ -240,3 +384,110 @@ describe('accumulation and purity', () => { expect(workouts).toEqual(before) }) }) + + +describe('warm-up flag in strength and fatigue', () => { + it('a warm-up set does not reset strength but still adds fatigue volume', () => { + const now = Date.UTC(2026, 7, 1, 12) + const oldWork = { id: 'w1', d: '2026-07-10', start: now - 20 * 86400000, unit: 'kg', + entries: [{ id: '1254', sets: [{ done: true, w: 80, r: 8 }] }] } + const warm = { id: 'w2', d: '2026-08-01', start: now - 3600000, unit: 'kg', + entries: [{ id: '1254', sets: [{ done: true, warmup: true, w: 20, r: 8 }] }] } + const workouts = [oldWork, warm] + const strength = strengthOf(workouts, now) + // the strength edge is 20 days old: the fresh warm-up must NOT be the latest training event + expect(strength.chest).toBeLessThan(1) + // but the warm-up still contributes to the fatigue stimulus (real mechanical work) + const fatigue = fatigueOf(workouts, now) + expect(fatigue.chest).toBeGreaterThan(0) + }) +}) + +describe('canonical loads and configured bodyweight', () => { + const loaded = EXDB.find(ex => { + const weights = musclesOf(ex) + return ex.bp !== 'cardio' && ex.eq !== 'body weight' + && Object.keys(weights).length === 1 && Object.values(weights)[0] === 1 + }) + const bodyweight = EXDB.find(ex => ex.bp !== 'cardio' && ex.eq === 'body weight') + if (!loaded || !bodyweight) throw new Error('recovery tests require loaded and bodyweight fixtures') + const loadedSlug = Object.keys(musclesOf(loaded))[0] + const bodyweightSlug = Object.keys(musclesOf(bodyweight))[0] + const stampedWorkout = ({ id, start, unit, weight, target, bw }) => ({ + d: new Date(start).toISOString(), start, unit, bw, + entries: [{ id, target, sets: [{ done: true, w: weight, r: 8 }] }], + }) + + it('gives kg and physically equivalent stamped-pound histories the same fatigue', () => { + const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 }) + const lb = stampedWorkout({ id: loaded.id, start: NOW, unit: 'lb', weight: 176.3696 }) + + expect(fatigueOf([lb], NOW, { unit: 'kg' })[loadedSlug]) + .toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6) + }) + + it('normalizes mixed stamped units before computing the causal reference volume', () => { + const starts = [NOW - 3 * DAY, NOW - 2 * DAY, NOW - DAY, NOW] + const kg = starts.map(start => stampedWorkout({ id: loaded.id, start, unit: 'kg', weight: 80 })) + const mixed = starts.map((start, i) => stampedWorkout({ + id: loaded.id, start, unit: i % 2 ? 'lb' : 'kg', weight: i % 2 ? 176.3696 : 80, + })) + + expect(fatigueOf(mixed, NOW, { unit: 'kg' })[loadedSlug]) + .toBeCloseTo(fatigueOf(kg, NOW, { unit: 'kg' })[loadedSlug], 6) + }) + + it('treats an unstamped legacy history as being in the profile unit', () => { + const kg = stampedWorkout({ id: loaded.id, start: NOW, unit: 'kg', weight: 80 }) + const legacyLb = { ...kg, unit: undefined, entries: [{ ...kg.entries[0], sets: [{ done: true, w: 176.3696, r: 8 }] }] } + + expect(fatigueOf([legacyLb], NOW, { unit: 'lb' })[loadedSlug]) + .toBeCloseTo(fatigueOf([kg], NOW, { unit: 'kg' })[loadedSlug], 6) + }) + + it('uses configured bodyweight for a non-catalogue bodyweight target', () => { + const workout = stampedWorkout({ + id: loaded.id, start: NOW, unit: 'kg', weight: 0, + target: { bodyweight: true }, bw: 80, + }) + + expect(fatigueOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBeGreaterThan(0) + expect(strengthOf([workout], NOW, { unit: 'kg' })[loadedSlug]).toBe(1) + }) + + it('adds external load to bodyweight instead of replacing the body mass', () => { + const unloaded = stampedWorkout({ id: bodyweight.id, start: NOW, unit: 'kg', weight: 0, bw: 80 }) + const loadedSet = { done: true, w: 10, r: 8 } + const added = { ...unloaded, entries: [{ ...unloaded.entries[0], sets: [loadedSet] }] } + + expect(fatigueOf([added], NOW, { unit: 'kg' })[bodyweightSlug]) + .toBeGreaterThan(fatigueOf([unloaded], NOW, { unit: 'kg' })[bodyweightSlug]) + }) + + it('lets explicitly configured custom bodyweight work reset strength', () => { + const id = 'recovery-custom-bodyweight' + registerCustom([{ id, n: 'Custom bodyweight', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }]) + try { + const workout = stampedWorkout({ id, start: NOW, unit: 'kg', weight: 0, bw: 80, target: { bodyweight: true } }) + expect(fatigueOf([workout], NOW, { unit: 'kg' }).chest).toBeGreaterThan(0) + expect(strengthOf([workout], NOW, { unit: 'kg' }).chest).toBe(1) + } finally { + registerCustom([]) + } + }) + + it('counts a default custom zero-load ring push-up for fatigue and load-blind strength', () => { + const id = 'recovery-ring-push-up' + registerCustom([{ id, n: 'Ring push-up', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }]) + try { + const workout = workoutAt(id, NOW, [ + { done: true, w: 0, r: 20 }, + { done: true, w: 0, r: 20 }, + ]) + expect(fatigueOf([workout], NOW).chest).toBeCloseTo(1 - Math.exp(-2 / 3), 10) + expect(strengthOf([workout], NOW).chest).toBe(1) + } finally { + registerCustom([]) + } + }) +}) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index af08fba..6b76ac8 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -37,7 +37,7 @@ function latestMuscleTraining(workouts) { return latest } -const FATIGUE_LEVELS = [ +export const FATIGUE_LEVELS = [ { at: 0, level: 0 }, { at: 0.15, level: 1 }, { at: 0.25, level: 2 }, @@ -45,7 +45,7 @@ const FATIGUE_LEVELS = [ { at: 0.55, level: 4, exclusive: true }, ] -const STRENGTH_LEVELS = [ +export const STRENGTH_LEVELS = [ { at: STRENGTH_FLOOR, level: 0 }, { at: 0.625, level: 1 }, { at: 0.75, level: 2 }, @@ -100,8 +100,16 @@ function MuscleBalance({ S }) { const [sel, setSel] = useState(null) const now = useNow() const workouts = S.workouts - const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now]) - const strength = useMemo(() => strengthOf(workouts, now), [workouts, now]) + // The user's own last registered bodyweight drives bodyweight-exercise tonnage. + const bodyweightKg = useMemo(() => { + const entries = S.bodyweight || [] + if (!entries.length) return null + const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1) + if (!last || !(last.w > 0)) return null + return S.unit === 'lb' ? last.w * 0.45359237 : last.w + }, [S.bodyweight, S.unit]) + const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit]) + const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit]) const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts]) const { worked: strengthOrder } = rankOf(strength) const detrained = strengthOrder.filter(slug => strength[slug] < 1) diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index bf06701..70d1e0a 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -1,11 +1,11 @@ import React, { act } from 'react' import { createRoot } from 'react-dom/client' -import { parseHTML } from 'linkedom' +import { Window } from 'happy-dom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { MUSCLES, MUSCLE_NAME, levelsOf, rankOf } from '../lib/muscles.js' +import { MUSCLES, levelsOf } from '../lib/muscles.js' import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js' import { fatigueStateOf } from '../lib/recovery-view.js' -import Stats, { weeksSinceTraining } from './Stats.jsx' +import Stats from './Stats.jsx' const DAY = 86400000 const HOUR = 3600000 @@ -35,7 +35,7 @@ vi.mock('../components/BodyMap.jsx', () => ({ default: props => { mocks.maps.push(props) React.useEffect(() => { - mocks.mapMounts++ + mocks.mapMounts += 1 return () => {} }, []) return React.createElement( @@ -59,7 +59,7 @@ function iso(timestamp) { } function set(done, extra = {}) { - return { done, w: 10, r: 8, unit: 'kg', ...extra } + return { done, w: 80, r: 8, unit: 'kg', ...extra } } function workout(id, start, entries) { @@ -71,49 +71,34 @@ function entry(id, sets) { } function lifecycleWorkouts(now = BASE_NOW) { - // A 6-set chest day on the saturating curve crosses .5 at ~55.05 hours, so the edge - // flips fatigued -> recovering after one 60-second interval tick. - const fatigueEdge = now - (36 * Math.log2(6 / (3 * Math.LN2)) * HOUR - 30000) - // This completed set is in the initial 30-day Balance window, then ages out after one tick. + // The old one-set session lowers the causal reference seen by the six-set session. Position + // that newer stimulus 30 seconds before its .5 crossing so the real interval update flips it. + const weightedSet = 640 * (30 / 38) ** 1.5 + const referenceAfterOldSession = 2000 + (weightedSet - 2000) / 3 + const fatigueEdge = now - ( + 36 * Math.log2((6 * weightedSet / referenceAfterOldSession) / Math.LN2) * HOUR - 30000 + ) const balanceEdge = now - (30 * DAY - 30000) - // The 14-day strength edge becomes sub-full after one tick. const strengthEdge = now - (14 * DAY - 30000) - // This completed event must remain the latest training event for abs: the newer set is undone. - const absCompleted = now - 20 * DAY - const absUndone = now - DAY return [ workout('fatigue-edge', fatigueEdge, [entry('1254', Array.from({ length: 6 }, () => set(true, { rir: 0 })))]), workout('balance-edge', balanceEdge, [entry('1254', [set(true, { rir: 2 })])]), workout('strength-edge', strengthEdge, [entry('1001', [set(true, { rir: 2 })])]), - workout('abs-completed', absCompleted, [entry('1002', [set(true, { rir: 2 })])]), - workout('abs-undone', absUndone, [entry('1002', [set(false, { rir: 0 })])]), + workout('abs-completed', now - 20 * DAY, [entry('1002', [set(true, { rir: 2 })])]), + workout('abs-undone', now - DAY, [entry('1002', [set(false, { rir: 0 })])]), ] } function allFatiguedWorkout(now = BASE_NOW) { - // Eight completed sets per exercise: on the saturating curve every involved muscle gets - // raw >= 3.2 (0.4 x 8), i.e. a fatigue value above the .55 top band regardless of the - // catalogue's secondary-muscle metadata. const ids = [ - ['1018', 1], // trapezius - ['1012', 1], // deltoids - ['1167', 1], // chest - ['1013', 1], // upper-back - ['3011', 1], // serratus - ['1413', 1], // biceps - ['1399', 1], // triceps - ['1016', 1], // forearm - ['1005', 2], // abs + obliques - ['1010', 1], // lower-back - ['1003', 1], // gluteal - ['1001', 1], // quadriceps - ['1511', 1], // hamstring - ['1494', 1], // adductors - ['1002', 2], // abs + hip-flexors - ['1000', 1], // calves - ['1396', 2], // calves + tibialis + '1018', '1012', '1167', '1013', '3011', '1413', '1399', '1016', '1005', + '1010', '1003', '1001', '1511', '1494', '1002', '1000', '1396', ] - return workout('all-fatigued', now, ids.map(([id]) => entry(id, Array.from({ length: 8 }, () => set(true))))) + return workout( + 'all-fatigued', + now, + ids.map(id => entry(id, Array.from({ length: 12 }, () => set(true)))), + ) } function allSubfullWorkout(now = BASE_NOW) { @@ -121,20 +106,24 @@ function allSubfullWorkout(now = BASE_NOW) { } function resetFixture(workouts = lifecycleWorkouts()) { + mocks.S.unit = 'kg' + mocks.S.bodyweight = [] mocks.S.workouts = workouts mocks.maps.length = 0 mocks.mapMounts = 0 } function installDom() { - const parsed = parseHTML('
') - dom = parsed.window + dom = new Window({ url: 'http://localhost/' }) globalThis.window = dom globalThis.document = dom.document Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator }) - for (const key of ['HTMLElement', 'Node', 'Element', 'Event']) globalThis[key] = dom[key] + for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) { + globalThis[key] = dom[key] + } globalThis.IS_REACT_ACT_ENVIRONMENT = true - container = document.getElementById('root') + container = document.createElement('div') + document.body.append(container) root = createRoot(container) } @@ -148,6 +137,7 @@ async function unmountStats() { await act(async () => { root.unmount() }) root = null container = null + dom.close() dom = null } @@ -166,36 +156,20 @@ function viewButton(text) { } function balanceRangeButton(text) { - const segments = muscleCard().querySelectorAll('.seg') - return buttonWithText(segments[1], text) + return buttonWithText(muscleCard().querySelectorAll('.seg')[1], text) } async function click(button) { expect(button, `expected a button named ${button?.textContent || 'unknown'}`).toBeTruthy() - await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) }) + await act(async () => { button.dispatchEvent(new dom.MouseEvent('click', { bubbles: true })) }) } async function tick(milliseconds) { await act(async () => { await vi.advanceTimersByTimeAsync(milliseconds) }) } -function lastMap() { - return mocks.maps.at(-1) -} - -function expectPressed(button) { - expect(button?.getAttribute('aria-pressed')).toBe('true') -} - -function strengthRows() { - return [...muscleCard().querySelectorAll('.mrow .nm')].map(node => node.textContent.trim()) -} - -afterEach(async () => { - await unmountStats() - vi.useRealTimers() - vi.restoreAllMocks() -}) +const lastMap = () => mocks.maps.at(-1) +const expectPressed = button => expect(button?.getAttribute('aria-pressed')).toBe('true') beforeEach(() => { vi.useFakeTimers() @@ -203,41 +177,48 @@ beforeEach(() => { resetFixture() }) -describe('Stats muscle recovery view runtime', () => { - it('starts in Balance and preserves range, hard filter, and selected muscle through every real view transition', async () => { - await mountStats() - const card = muscleCard() +afterEach(async () => { + await unmountStats() + vi.useRealTimers() + vi.restoreAllMocks() +}) - expectPressed(buttonWithText(card, 'Muscle balance')) - expectPressed(buttonWithText(card, 'Week')) +describe('Stats muscle recovery view runtime', () => { + it('dispatches real clicks through Balance, Fatigue, and Strength and preserves selection', async () => { + await mountStats() + expectPressed(viewButton('Muscle balance')) + expectPressed(balanceRangeButton('Week')) await click(balanceRangeButton('30d')) - await click(buttonWithText(card, 'All')) - await click(card.querySelector('[data-muscle="chest"]')) - expectPressed(balanceRangeButton('30d')) + await click(buttonWithText(muscleCard(), 'All')) + await click(muscleCard().querySelector('[data-muscle="chest"]')) expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() - expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() await click(viewButton('Fatigue')) + expectPressed(viewButton('Fatigue')) + expect(lastMap().thresholds).toBeTruthy() expect(container.textContent).toContain('Fatigue shows how recently each muscle was trained. High means rest.') - await click(viewButton('Strength')) - expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.') - await click(viewButton('Muscle balance')) + expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() + await click(viewButton('Strength')) + expectPressed(viewButton('Strength')) + expect(lastMap().thresholds.at(-1)).toEqual({ at: 1, level: 4 }) + expect(container.textContent).toContain('Strength shows retained muscle strength. Train again to reset it.') + + await click(viewButton('Muscle balance')) expectPressed(balanceRangeButton('30d')) expect(buttonWithText(muscleCard(), 'Hard')).toBeTruthy() - expect(container.querySelector('[data-selected-muscle="chest"]')).toBeTruthy() expect(lastMap().selected).toBe('chest') expect(lastMap().load.chest).toBe(7) }) - it('refreshes fatigue presentation, Balance 30-day filtering, and the mounted tree on the 60-second tick', async () => { + it('updates the rendered Fatigue map and Balance window on the real 60-second interval', async () => { await mountStats() await click(balanceRangeButton('30d')) await click(viewButton('Fatigue')) await click(muscleCard().querySelector('[data-muscle="chest"]')) - const beforeTickMounts = mocks.mapMounts + const mountsBeforeTick = mocks.mapMounts const beforeTick = lastMap().load.chest expect(fatigueStateOf(beforeTick)).toBe(FATIGUE_STATES.FATIGUED) expect(container.textContent).toContain('Fatigued') @@ -245,43 +226,34 @@ describe('Stats muscle recovery view runtime', () => { await tick(60000) const afterTick = lastMap().load.chest - expect(mocks.mapMounts).toBe(beforeTickMounts) - expect(afterTick).toBeLessThan(0.5) + expect(mocks.mapMounts).toBe(mountsBeforeTick) + expect(afterTick).toBeLessThan(beforeTick) expect(fatigueStateOf(afterTick)).toBe(FATIGUE_STATES.RECOVERING) expect(container.textContent).toContain('Recovering') await click(viewButton('Strength')) expect(lastMap().load.quadriceps).toBeLessThan(1) - expect(strengthRows()).toContain('Quads') - await click(viewButton('Muscle balance')) expect(lastMap().load.chest).toBe(6) - expectPressed(balanceRangeButton('30d')) }) - it('ignores an undone latest set, floors rendered training age, and follows production rankOf ordering', async () => { + it('derives a pound-profile bodyweight in kg and passes it into the rendered Fatigue map', async () => { + const bodyweightWorkout = workout('bodyweight', BASE_NOW, [ + entry('0001', [{ done: true, w: 0, r: 10 }]), + ]) + resetFixture([bodyweightWorkout]) + mocks.S.unit = 'lb' + mocks.S.bodyweight = [{ d: '2026-01-20', w: 180 }, { d: '2026-01-22', w: 220.462262 }] + await mountStats() - await click(viewButton('Strength')) + await click(viewButton('Fatigue')) - const load = lastMap().load - const expectedRows = rankOf(load).worked - .filter(slug => load[slug] < 1) - .map(slug => MUSCLE_NAME[slug]) - expect(strengthRows()).toEqual(expectedRows) - - // The newer abs row is undone, so the rendered hint uses the completed event from 20 days ago. - expect(container.textContent).toContain('1 sets') - - // The production helper used by Stats' rendered strength hint floors six elapsed days to zero. - expect(weeksSinceTraining(BASE_NOW, BASE_NOW - 6 * DAY)).toBe(0) + // 220.462262 lb ~= 100 kg; ten reps score 1000 kg against the initial 2000 kg reference. + expect(lastMap().load.abs).toBeCloseTo(1 - Math.exp(-0.5), 6) + expect(lastMap().thresholds).toBeTruthy() }) - it('uses production boundaries and fixed absolute bands for all-fatigued and all-subfull maps', async () => { - expect(fatigueStateOf(0.2499)).toBe(FATIGUE_STATES.READY) - expect(fatigueStateOf(0.25)).toBe(FATIGUE_STATES.RECOVERING) - expect(fatigueStateOf(0.5)).toBe(FATIGUE_STATES.RECOVERING) - expect(fatigueStateOf(0.5001)).toBe(FATIGUE_STATES.FATIGUED) - + it('renders fixed absolute bands through the actual Fatigue and Strength views', async () => { resetFixture([allFatiguedWorkout()]) await mountStats() await click(viewButton('Fatigue')) From 23a5b6c22892a67f34b631071459f4ce7d77246f Mon Sep 17 00:00:00 2001 From: Space-Hermes Date: Wed, 12 Aug 2026 17:43:20 +0200 Subject: [PATCH 43/58] fix: smaller same-area items from the review - future-dated clamp, LB_TO_KG export, value-based bodyweight guard --- frontend/src/lib/recovery.js | 6 +++--- frontend/src/lib/recovery.test.js | 12 ++++++++++++ frontend/src/views/Stats.jsx | 4 ++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index d73b345..5d63f00 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -66,7 +66,7 @@ function emptyMuscleMap(value) { const REP_CAP = 12 const epley1RM = (load, reps) => load * (1 + Math.min(reps || 1, REP_CAP) / 30) -const LB_TO_KG = 0.45359237 +export const LB_TO_KG = 0.45359237 function numeric(value) { if (value === null || value === undefined || value === '' || typeof value === 'boolean') return null @@ -139,7 +139,7 @@ function bodyweightConfigured(ex, entry, set, workout, opts = {}) { const added = kgOf(set?.w, unitOf(set, entry?.target, entry, workout, opts)) const hasBodyweightContext = numeric(workout?.bw) !== null || numeric(workout?.bodyweight) !== null - || Object.prototype.hasOwnProperty.call(opts, 'bodyweightKg') + || numeric(opts.bodyweightKg) !== null || numeric(opts.bodyweight) !== null || hasUnitStamp(set, entry?.target, entry, workout) return ex?.eq === 'body weight' && (added === 0 || hasBodyweightContext) @@ -253,7 +253,7 @@ function fatigueValue(events, now) { value += event.stimulus lastTimestamp = event.timestamp } - value *= halfLifeDecay(now - lastTimestamp, FATIGUE_HALF_LIFE_MS) + value *= halfLifeDecay(Math.max(0, now - lastTimestamp), FATIGUE_HALF_LIFE_MS) // Normalise the accumulated stimulus to a saturating fatigue level: more volume starts // higher but never pins, and the value fades asymptotically - no window-edge cliff. return 1 - Math.exp(-value) diff --git a/frontend/src/lib/recovery.test.js b/frontend/src/lib/recovery.test.js index 11c1bee..884f814 100644 --- a/frontend/src/lib/recovery.test.js +++ b/frontend/src/lib/recovery.test.js @@ -476,6 +476,18 @@ describe('canonical loads and configured bodyweight', () => { } }) + it('treats a future-dated workout as its own timestamp, never amplified', () => { + // A CSV import with a bad timezone can date a workout 10 days in the future. The final + // decay clamps the age to zero instead of exponentiating, so the session counts exactly + // like the same workout dated now - no 2^(10d/36h) ~ 102x amplification. + const future = doneWorkoutAt(SINGLE.id, NOW + 10 * DAY, 5) + const now = doneWorkoutAt(SINGLE.id, NOW, 5) + const futureValue = fatigueOf([future], NOW)[SINGLE_SLUG] + const nowValue = fatigueOf([now], NOW)[SINGLE_SLUG] + expect(futureValue).toBeCloseTo(nowValue, 10) + expect(futureValue).toBeLessThan(1) + }) + it('counts a default custom zero-load ring push-up for fatigue and load-blind strength', () => { const id = 'recovery-ring-push-up' registerCustom([{ id, n: 'Ring push-up', bp: 'chest', tg: 'chest', eq: 'custom', sm: [] }]) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 6b76ac8..14ef77b 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -11,7 +11,7 @@ import Heatmap from '../components/Heatmap.jsx' import Icon from '../components/Icon.jsx' import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx' import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' -import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js' +import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js' import { fatigueStateOf } from '../lib/recovery-view.js' import { e1rmSeries, best1RM } from '../lib/onerm.js' import { @@ -106,7 +106,7 @@ function MuscleBalance({ S }) { if (!entries.length) return null const last = entries.slice().sort((a, b) => String(a.d).localeCompare(String(b.d))).at(-1) if (!last || !(last.w > 0)) return null - return S.unit === 'lb' ? last.w * 0.45359237 : last.w + return S.unit === 'lb' ? last.w * LB_TO_KG : last.w }, [S.bodyweight, S.unit]) const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit]) const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit]) From 57f04febbe5236cfd49f4ac1d8694cb43a54c82d Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 20:13:35 +0200 Subject: [PATCH 44/58] feat(i18n): add strength-view strings to all locales --- frontend/src/locales/de.js | 4 ++++ frontend/src/locales/es.js | 4 ++++ frontend/src/locales/fr.js | 4 ++++ frontend/src/locales/hi.js | 4 ++++ frontend/src/locales/it.js | 4 ++++ frontend/src/locales/ko.js | 4 ++++ frontend/src/locales/pl.js | 4 ++++ frontend/src/locales/pt.js | 4 ++++ frontend/src/locales/ru.js | 4 ++++ frontend/src/locales/tr.js | 4 ++++ frontend/src/locales/zh.js | 4 ++++ 11 files changed, 44 insertions(+) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 779b301..9c06d2b 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -586,5 +586,9 @@ export default { '{0} sets · {1} work': '{0} Sätze · {1} Arbeit', 'Make superset with previous': 'Mit vorheriger Übung kombinieren', 'Make superset with next': 'Mit nächster Übung kombinieren', + "primary": "primär", + "secondary": "sekundär", + "No exercises with an estimated 1RM yet.": "Noch keine Übungen mit geschätztem 1RM.", + "Tap a muscle to see its exercises.": "Tippe auf einen Muskel, um seine Übungen zu sehen.", 'Unpair': 'Trennen' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index a80f623..ab2875e 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} series · {1} trabajo', 'Make superset with previous': 'Hacer superserie con anterior', 'Make superset with next': 'Hacer superserie con siguiente', + "primary": "principal", + "secondary": "secundario", + "No exercises with an estimated 1RM yet.": "Aún no hay ejercicios con 1RM estimado.", + "Tap a muscle to see its exercises.": "Toca un músculo para ver sus ejercicios.", 'Unpair': 'Desvincular' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index a9207b8..3d9e293 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} séries · {1} travail', 'Make superset with previous': 'Faire un superset avec le précédent', 'Make superset with next': 'Faire un superset avec le suivant', + "primary": "principal", + "secondary": "secondaire", + "No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.", + "Tap a muscle to see its exercises.": "Touchez un muscle pour voir ses exercices.", 'Unpair': 'Dissocier' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 60e2e2a..c166031 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} सेट · {1} काम', 'Make superset with previous': 'पिछले के साथ सुपरसेट', 'Make superset with next': 'अगले के साथ सुपरसेट', + "primary": "प्राथमिक", + "secondary": "द्वितीयक", + "No exercises with an estimated 1RM yet.": "अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।", + "Tap a muscle to see its exercises.": "व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।", 'Unpair': 'अलग करें' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index a9f01db..e5c9c77 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} serie · {1} lavoro', 'Make superset with previous': 'Superset con il precedente', 'Make superset with next': 'Superset con il successivo', + "primary": "primario", + "secondary": "secondario", + "No exercises with an estimated 1RM yet.": "Nessun esercizio con 1RM stimato finora.", + "Tap a muscle to see its exercises.": "Tocca un muscolo per vedere i suoi esercizi.", 'Unpair': 'Separa' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 6a811fd..028440f 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} 세트 · {1} 작업', 'Make superset with previous': '이전 운동과 슈퍼셋', 'Make superset with next': '다음 운동과 슈퍼셋', + "primary": "주동", + "secondary": "보조", + "No exercises with an estimated 1RM yet.": "추정 1RM이 있는 운동이 아직 없습니다.", + "Tap a muscle to see its exercises.": "근육을 눌러 해당 운동을 확인하세요.", 'Unpair': '분리' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index ddc2fa6..b4f437b 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} serii · {1} praca', 'Make superset with previous': 'Połącz z poprzednim', 'Make superset with next': 'Połącz z następnym', + "primary": "główny", + "secondary": "drugorzędny", + "No exercises with an estimated 1RM yet.": "Brak ćwiczeń z oszacowanym 1RM.", + "Tap a muscle to see its exercises.": "Dotknij mięśnia, aby zobaczyć jego ćwiczenia.", 'Unpair': 'Rozłącz' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 3e50cf5..148ed63 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} séries · {1} trabalho', 'Make superset with previous': 'Fazer superset com o anterior', 'Make superset with next': 'Fazer superset com o próximo', + "primary": "primário", + "secondary": "secundário", + "No exercises with an estimated 1RM yet.": "Ainda não há exercícios com 1RM estimado.", + "Tap a muscle to see its exercises.": "Toque num músculo para ver os seus exercícios.", 'Unpair': 'Desfazer' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 1dbc915..7893621 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} подходов · {1} рабочих', 'Make superset with previous': 'Суперсет с предыдущим', 'Make superset with next': 'Суперсет со следующим', + "primary": "основная", + "secondary": "вспомогательная", + "No exercises with an estimated 1RM yet.": "Пока нет упражнений с расчётным 1ПМ.", + "Tap a muscle to see its exercises.": "Нажмите на мышцу, чтобы увидеть её упражнения.", 'Unpair': 'Разъединить' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index b3c3879..e9839ac 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} set · {1} çalışma', 'Make superset with previous': 'Öncekiyle superset yap', 'Make superset with next': 'Sonrakiyle superset yap', + "primary": "birincil", + "secondary": "ikincil", + "No exercises with an estimated 1RM yet.": "Henüz tahmini 1RM olan egzersiz yok.", + "Tap a muscle to see its exercises.": "Egzersizlerini görmek için bir kas seçin.", 'Unpair': 'Ayır' } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 0157fa2..f01c212 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -569,5 +569,9 @@ export default { '{0} sets · {1} work': '{0} 组 · {1} 工作', 'Make superset with previous': '与上一个组成超级组', 'Make superset with next': '与下一个组成超级组', + "primary": "主要", + "secondary": "次要", + "No exercises with an estimated 1RM yet.": "暂无估算1RM的动作。", + "Tap a muscle to see its exercises.": "点击肌肉查看其动作。", 'Unpair': '取消组合' } From f3ba7de47931f6e02cff9700cdcaf2ec5539f4fa Mon Sep 17 00:00:00 2001 From: Space Hermes Date: Wed, 12 Aug 2026 20:18:05 +0200 Subject: [PATCH 45/58] feat: add strength exercise view and history snapshots --- frontend/src/lib/finish-workout.js | 29 ++++ frontend/src/lib/finish-workout.test.js | 38 +++++ frontend/src/lib/history.js | 80 +++++++-- frontend/src/lib/history.test.js | 138 ++++++++++----- frontend/src/lib/muscles.js | 121 ++++++++++++-- frontend/src/lib/onerm.js | 3 +- frontend/src/lib/recovery.js | 6 +- frontend/src/lib/strength-exercises.js | 143 ++++++++++++++++ frontend/src/lib/strength-exercises.test.js | 176 ++++++++++++++++++++ frontend/src/lib/workout-model.js | 74 ++++++++ frontend/src/sheets.jsx | 32 ++-- frontend/src/views/Stats.jsx | 109 ++++++++---- 12 files changed, 831 insertions(+), 118 deletions(-) create mode 100644 frontend/src/lib/finish-workout.js create mode 100644 frontend/src/lib/finish-workout.test.js create mode 100644 frontend/src/lib/strength-exercises.js create mode 100644 frontend/src/lib/strength-exercises.test.js create mode 100644 frontend/src/lib/workout-model.js diff --git a/frontend/src/lib/finish-workout.js b/frontend/src/lib/finish-workout.js new file mode 100644 index 0000000..f34f92b --- /dev/null +++ b/frontend/src/lib/finish-workout.js @@ -0,0 +1,29 @@ +// The persisted boundary for a finished session. Keep this pure so compatibility tests can +// exercise the exact shape the UI writes without mounting React or mutating store state. +export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snapshotFor } = {}) { + const entries = (active?.entries || []).map(entry => { + const completed = { + id: entry.id, + sets: entry.sets, + topW: entry.topW || null, + target: entry.target || null, + } + const snapshot = typeof snapshotFor === 'function' ? snapshotFor(entry) : null + if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) { + completed.muscleSnapshot = { ...snapshot } + } + return completed + }).filter(entry => entry.sets.some(set => set.done)) + + return { + id: active.id, + d: active.d, + start: active.start, + end, + routineId: active.routineId, + name: active.name, + bw: active.bw, + entries, + prs, + } +} diff --git a/frontend/src/lib/finish-workout.test.js b/frontend/src/lib/finish-workout.test.js new file mode 100644 index 0000000..2dbe951 --- /dev/null +++ b/frontend/src/lib/finish-workout.test.js @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { buildCompletedWorkout } from './finish-workout.js' + +describe('completed workout boundary', () => { + it('builds the same legacy-shaped record doFinishWorkout stores and keeps it visible', () => { + const active = { + id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Push', bw: 80, + entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }], + } + const completed = buildCompletedWorkout(active, { end: 2000, prs: [] }) + expect(completed).toEqual({ + id: 'active-1', d: '2026-08-08', start: 1000, end: 2000, routineId: 'routine-1', name: 'Push', bw: 80, + entries: [{ id: '0025', sets: [{ done: true, w: 60, r: 8 }], topW: 60, target: { sets: 1, reps: 8 } }], + prs: [] + }) + }) + + it('persists a muscle snapshot only when the caller supplies one', () => { + const active = { + id: 'active-1', d: '2026-08-08', start: 1000, + entries: [ + { id: 'catalogue', sets: [{ done: true }] }, + { id: 'custom', sets: [{ done: true }] }, + ], + } + const completed = buildCompletedWorkout(active, { + end: 2000, + snapshotFor: entry => entry.id === 'custom' + ? { n: 'Custom lift', muscleWeights: { chest: 1 } } + : null, + }) + + expect(completed.entries[0]).not.toHaveProperty('muscleSnapshot') + expect(completed.entries[1].muscleSnapshot).toEqual({ + n: 'Custom lift', muscleWeights: { chest: 1 }, + }) + }) +}) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index d261345..9c440ae 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -1,6 +1,16 @@ // Pure helpers over the state object S (ported 1:1 from the vanilla app). import { todayISO, isoOf, weekKey, fmtNum } from './format.js' import { isCardio, isBodyweightEq } from './exercises.js' +import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js' +const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {} +// Completed-state-independent work rows whose authoritative mode matches the requested mode. +const workRowsForMode = (entry = {}, mode = 'reps') => { + const source = objectOf(entry) + const target = objectOf(source.target || source) + const expectedMode = normalizeMode(mode, 'reps') + return (Array.isArray(source.sets) ? source.sets : []) + .filter(set => phaseForSet(set) === 'work' && modeForSet(set, target) === expectedMode) +} // i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no // React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore // for the hook — and it re-exports this very `t` from core, so nothing changes here except what @@ -224,10 +234,7 @@ export function freestyleConfig(S, cfg) { export function bestWeightFor(S, exId) { let best = 0 S.workouts.forEach(w => w.entries.forEach(e => { - if (e.id === exId) { - e.sets.forEach(s => { if (s.done && s.w > best) best = s.w }) - if (e.topW && e.topW > best) best = e.topW - } + if (e.id === exId) best = Math.max(best, bestWeightForEntry(e)) })) return best } @@ -330,10 +337,10 @@ export function streakWeeks(S) { * undone take the new value (null deletes the key). Done sets are never rewritten. */ export function cascadeWeight(rows, from, value) { - const warm = !!rows[from]?.warmup + const warm = isWarmupRow(rows[from]) const next = rows.slice() for (let j = from + 1; j < next.length; j++) { - if (!!next[j].warmup === warm && !next[j].done) { + if (isWarmupRow(next[j]) === warm && !next[j].done) { if (value == null) delete next[j].w else next[j].w = value } @@ -343,14 +350,14 @@ export function cascadeWeight(rows, from, value) { /** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */ export function insertWarmupRow(rows, mode, target) { - const firstWork = rows.findIndex(x => !x.warmup) + const firstWork = rows.findIndex(x => !isWarmupRow(x)) const at = firstWork === -1 ? rows.length : firstWork const l = rows[at - 1] || rows[rows.length - 1] const warm = mode === 'cardio' - ? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, warmup: true } + ? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true } : mode === 'time' - ? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, warmup: true } - : { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, warmup: true } + ? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true } + : { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true } const next = rows.slice() next.splice(at, 0, warm) return next @@ -367,6 +374,57 @@ export function removeRowAt(rows, i) { /** Completed non-warm-up sets across a workout's entries. */ export function workSetsDone(w) { return (w?.entries || []).reduce( - (n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0, + (n, e) => n + (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0, ) } + +const METRIC_MODES = ['reps', 'time', 'cardio'] +const completedRowsForMode = (entry, mode) => workRowsForMode(entry, mode).filter(s => s.done === true && !isWarmupRow(s)) + +export function metricRowsForEntry(entry, mode) { + const requested = typeof mode === 'string' ? mode.trim().toLowerCase() : '' + const resolved = METRIC_MODES.includes(requested) ? requested : metricModeForEntry(entry) + return resolved ? completedRowsForMode(entry, resolved) : [] +} + +/** The authoritative metric for an entry; reps rows take precedence over timed/cardio rows. */ + +export function metricModeForEntry(entry, fallback = null) { + for (const mode of METRIC_MODES) { + if (completedRowsForMode(entry, mode).length) return mode + } + return modeForEntry(entry, fallback) +} + +/** Best load from completed work rows, with a guarded reps-only legacy topW fallback. */ + +export function bestWeightForEntry(entry = {}) { + const target = entry.target || entry + const workRows = Array.isArray(entry.sets) + ? entry.sets.filter(s => phaseForSet(s) === 'work') + : [] + const repsRows = metricRowsForEntry(entry, 'reps') + if (!repsRows.length) { + return workRows.reduce((best, set) => { + if (set?.done !== true || isWarmupRow(set)) return best + const weight = Number(set.w) + return Number.isFinite(weight) && weight > best ? weight : best + }, 0) + } + + let best = 0 + repsRows.forEach(set => { + const weight = Number(set?.w) + if (Number.isFinite(weight) && weight > best) best = weight + }) + + const parentMode = modeForSet({}, target) + const hasNonRepsWorkRow = workRows.some(set => modeForSet(set, target) !== 'reps') + const hasWarmupRow = Array.isArray(entry.sets) && entry.sets.some(isWarmupRow) + const topWeight = Number(entry.topW) + // topW predates phase-tagged warm-ups. It remains a fallback for legacy all-work records, + // but cannot override resolved work rows once any warm-up marker exists. + if (parentMode === 'reps' && !hasNonRepsWorkRow && !hasWarmupRow + && Number.isFinite(topWeight) && topWeight > best) best = topWeight + return best +} diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 68d1f0a..fed50f5 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js' +import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -9,49 +9,6 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').id const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id const BW = EXDB.find(e => e.eq === 'body weight').id -describe('superset editing', () => { - it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => { - const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] - - const paired = pairAdjacent(entries, 1, 2, 'sg-new') - - expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }]) - expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) - expect(supersetUnits(paired)).toEqual([[0], [1, 2]]) - }) - - it('merges both contiguous groups when their boundary entries are paired', () => { - const entries = [ - { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' }, - { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' } - ] - - const merged = pairAdjacent(entries, 1, 2) - - expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left']) - expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right']) - }) - - it('unpairs one entry and removes sg values left without an adjacent partner', () => { - const entries = [ - { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' }, - { id: 'd', sg: 'orphan' } - ] - - const unpaired = unpairSuperset(entries, 1) - - expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]) - expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan']) - }) - - it('rejects a non-adjacent pairing request', () => { - const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] - - expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/) - expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) - }) -}) - describe('modeOf', () => { it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => { expect(modeOf({ id: CARDIO })).toBe('cardio') @@ -520,6 +477,99 @@ describe('workoutVolume', () => { const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] } expect(workoutVolume(w)).toBe(0) }) + + it('recognizes both warm-up schemas in work-set counts', () => { + const w = { + unit: 'kg', + entries: [{ + id: LIFT, + unit: 'kg', + sets: [ + { warmup: true, unit: 'kg', w: 20, r: 5, done: true }, + { phase: 'warmup', unit: 'kg', w: 30, r: 5, done: true }, + { phase: 'work', unit: 'kg', w: 60, r: 5, done: true }, + ], + }], + } + expect(workSetsDone(w)).toBe(1) + }) + + it('does not use a warm-up as the previous best working weight', () => { + expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [ + { phase: 'warmup', done: true, w: 120 }, + { phase: 'work', done: true, w: 80 }, + ] }] }] }, LIFT)).toBe(80) + expect(bestWeightFor({ workouts: [{ entries: [{ id: LIFT, topW: 120, sets: [ + { phase: 'warmup', done: true, w: 120 }, + ] }] }] }, LIFT)).toBe(0) + }) + + it('uses completed non-warm-up load for timed entries', () => { + expect(bestWeightForEntry({ target: { mode: 'time' }, topW: 200, sets: [ + { phase: 'warmup', sec: 30, w: 30, done: true }, + { phase: 'work', sec: 60, w: 20, done: true }, + { phase: 'work', sec: 75, w: 25, done: true }, + { phase: 'work', sec: 90, w: 40, done: false }, + ] })).toBe(25) + }) + + it('does not report a repeated weighted timed hold as a new load PR (blocker 3)', () => { + const prior = { + id: LIFT, + target: { mode: 'time' }, + sets: [{ phase: 'work', sec: 60, w: 20, done: true }], + } + const repeated = { + id: LIFT, + target: { mode: 'time' }, + sets: [{ phase: 'work', sec: 60, w: 20, done: true }], + } + const state = { workouts: [{ entries: [prior] }] } + const repeatedWeight = Math.max(0, ...repeated.sets.filter(set => set.done).map(set => set.w || 0)) + + expect(bestWeightForEntry(prior)).toBe(20) + expect(repeatedWeight > bestWeightFor(state, LIFT)).toBe(false) + }) +}) + +describe('superset editing', () => { + it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + const paired = pairAdjacent(entries, 1, 2, 'sg-new') + + expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }]) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + expect(supersetUnits(paired)).toEqual([[0], [1, 2]]) + }) + + it('merges both contiguous groups when their boundary entries are paired', () => { + const entries = [ + { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' }, + { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' } + ] + const merged = pairAdjacent(entries, 1, 2) + + expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left']) + expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right']) + }) + + it('unpairs one entry and removes sg values left without an adjacent partner', () => { + const entries = [ + { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' }, + { id: 'd', sg: 'orphan' } + ] + const unpaired = unpairSuperset(entries, 1) + + expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]) + expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan']) + }) + + it('rejects a non-adjacent pairing request', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + + expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + }) }) diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index 00927a2..2120443 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -7,7 +7,8 @@ // map can actually draw, via ALIAS below. Anything genuinely undrawable (hands, // ankles, "cardiovascular system") maps to null and is dropped rather than guessed at. -import { EXIDX , smOf } from './exercises.js' +import { isWarmupRow } from './workout-model.js' +import { EXIDX, smOf } from './exercises.js' // The muscles a map can shade, in head-to-toe order — also the order of any list // built from them, so "what am I neglecting" reads top-down like a body. @@ -69,21 +70,118 @@ const BY_BODYPART = { const SECONDARY = 0.4 // a supporting muscle counts this much against a primary -/** Muscles one exercise trains: { slug: 0…1 }. */ +const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value] + +// Completed history entries may retain a nested snapshot after their custom exercise is +// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle +// metadata of its own, while keeping direct/legacy entry fields authoritative when present. +function metadataOf(ex) { + if (!ex || typeof ex !== 'object') return ex + const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key)) + || [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '') + return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot) + ? ex.muscleSnapshot + : ex +} + +function explicitGroupsOf(ex) { + if (!ex || typeof ex !== 'object') return null + if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) { + const groups = arrayOf(ex.muscleGroups) + return groups.length ? groups : null + } + if (Object.prototype.hasOwnProperty.call(ex, 'muscles')) { + const groups = arrayOf(ex.muscles) + return groups.length ? groups : null + } + if (Object.prototype.hasOwnProperty.call(ex, 'targetMuscles')) { + const groups = arrayOf(ex.targetMuscles) + return groups.length ? groups : null + } + return null +} + +/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */ +export function hasExplicitMuscleMetadata(ex) { + const source = metadataOf(ex) + if (!source || typeof source !== 'object') return false + const groups = explicitGroupsOf(source) + if (groups && groups.some(value => canonicalMuscle(value))) return true + return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value)) +} + +function canonicalMuscle(value) { + const name = String(value || '').toLowerCase().trim() + if (MUSCLES.includes(name)) return name + return ALIAS[name] || null +} + +/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */ +export function muscleGroupsOf(ex) { + const sourceEx = metadataOf(ex) + const explicit = explicitGroupsOf(sourceEx) + const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))] + const out = [] + source.forEach(value => { + const slug = canonicalMuscle(value) + if (slug && !out.includes(slug)) out.push(slug) + }) + if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) }) + return out +} + +export const normalizeMuscleGroups = muscleGroupsOf + +/** True when any requested group matches; an empty request is an intentionally unfiltered query. */ +export function matchesMuscleGroups(ex, requested) { + const wanted = arrayOf(requested).map(canonicalMuscle).filter(Boolean) + if (!wanted.length) return true + const groups = new Set(muscleGroupsOf(ex)) + return wanted.some(group => groups.has(group)) +} + +/** Muscles one exercise trains: { slug: 0…1 }. Duplicate metadata never adds load twice. */ export function musclesOf(ex) { if (!ex) return {} + const sourceEx = metadataOf(ex) + if (sourceEx !== ex) return musclesOf(sourceEx) + if (ex.muscleWeights && typeof ex.muscleWeights === 'object' && !Array.isArray(ex.muscleWeights)) { + const snapshot = {} + MUSCLES.forEach(slug => { + const weight = Number(ex.muscleWeights[slug]) + if (Number.isFinite(weight) && weight > 0) snapshot[slug] = weight + }) + if (Object.keys(snapshot).length) return snapshot + } const out = {} const add = (name, w) => { - const slug = ALIAS[String(name || '').toLowerCase().trim()] + const slug = canonicalMuscle(name) if (slug) out[slug] = Math.max(out[slug] || 0, w) } - add(ex.tg, 1) - ;smOf(ex).forEach(m => add(m, SECONDARY)) + const explicit = explicitGroupsOf(ex) + if (explicit) explicit.forEach(m => add(m, 1)) + else { + add(ex.tg, 1) + add(ex.mg, SECONDARY) + arrayOf(smOf(ex)).forEach(m => add(m, SECONDARY)) + } // Nothing recognised (custom exercises, or a target we don't draw) — use the body part. if (!Object.keys(out).length) Object.assign(out, BY_BODYPART[ex.bp] || {}) return out } +/** Snapshot display and weighted muscle metadata into a completed history entry. */ +export function exerciseMuscleSnapshot(ex) { + if (!ex || typeof ex !== 'object') return {} + const out = {} + if (ex.n != null) out.n = ex.n + if (ex.bp != null) out.bp = ex.bp + const weights = musclesOf(ex) + if (Object.keys(weights).length) out.muscleWeights = { ...weights } + if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)] + return out +} + /** * Training load per muscle, in "effective sets". * `items` is [{ id, sets }] — sets being a count, so a 4×8 bench press weighs four @@ -92,9 +190,12 @@ export function musclesOf(ex) { */ export function loadOf(items) { const load = {} - items.forEach(({ id, sets }) => { + items.forEach(item => { + const { id, sets } = item || {} if (!sets) return - const m = musclesOf(EXIDX[id]) + const historical = item.ex || item.exercise + const source = historical?.muscleWeights ? historical : (EXIDX[id] || historical || item) + const m = musclesOf(source) for (const slug in m) load[slug] = (load[slug] || 0) + m[slug] * sets }) return load @@ -108,15 +209,15 @@ export function loadOf(items) { */ export const loadOfWorkouts = (workouts, pick) => loadOf((workouts || []).flatMap(w => - (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length })))) + (w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length })))) /** Load a routine *would* produce, from its planned set counts. */ export const loadOfRoutine = routine => - loadOf((routine?.ex || []).map(c => ({ id: c.id, sets: c.sets || 1 }))) + loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 }))) /** Load for a workout still in progress — the sets ticked so far. */ export const loadOfActive = active => - loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length }))) + loadOf((active?.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length }))) /** * Shade buckets 0–4 per muscle. diff --git a/frontend/src/lib/onerm.js b/frontend/src/lib/onerm.js index c3a0b11..2602118 100644 --- a/frontend/src/lib/onerm.js +++ b/frontend/src/lib/onerm.js @@ -1,3 +1,4 @@ +import { isWarmupRow } from './workout-model.js' // Estimated one-rep max (issue #18). // // Deliberately knows nothing about the exercise database: an estimate needs a weight AND a @@ -44,7 +45,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) { export function bestSetOf(entry, formula = DEFAULT_FORMULA) { let best = null ;(entry?.sets || []).forEach(s => { - if (!s.done || s.warmup) return + if (!s.done || isWarmupRow(s)) return const est = estimate1RM(s.w, s.r, formula) if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) } }) diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index ebc8020..477c193 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -111,9 +111,13 @@ function fatigueValue(events, now) { * * @param {Array} workouts Workout history with `start`/`d` and entry set arrays. * @param {number} now Current time in milliseconds; injected to keep this function deterministic. + * @param {{unit?: string}} options Reserved profile-level options; unit is supplied at the UI boundary. * @returns {Record} Fatigue values keyed by every drawable muscle slug. */ -export function fatigueOf(workouts, now) { +export function fatigueOf(workouts, now, options = {}) { + // Keep the profile unit at this boundary for a future separately reviewed tonnage model. + // The current mainline set-count model is intentionally unit-independent. + void options.unit const current = Number(now) const cutoff = current - FATIGUE_SCAN_MS const stimuli = completedStimuli(workouts, timestamp => timestamp > cutoff) diff --git a/frontend/src/lib/strength-exercises.js b/frontend/src/lib/strength-exercises.js new file mode 100644 index 0000000..c4669a2 --- /dev/null +++ b/frontend/src/lib/strength-exercises.js @@ -0,0 +1,143 @@ +// Per-exercise rows for the Strength view: best estimated 1RM from the user's own logged +// sets, the exercise's OWN retained-strength decay (same 14-day plateau / 28-day half-life +// / 0.5 floor model as the muscle map, applied to the exercise's last done work set), and +// the expected CURRENT 1RM (= estimate x decay). The body map keeps the per-muscle model; +// the exercise list deliberately reads per-exercise, so an old exercise shows its own +// decline even when its muscle is kept fresh by other work. Muscle mapping is +// catalogue-first (EXIDX), exactly like the fatigue/strength maps, falling back to the +// logged snapshot (muscleWeights) for exercises no longer in the catalogue. +import { best1RM } from './onerm.js' +import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay } from './recovery.js' +import { musclesOf } from './muscles.js' +import { EXIDX } from './exercises.js' +import { isWarmupRow } from './workout-model.js' + +const round1 = value => Math.round(value * 10) / 10 + +// Same retained-strength curve the muscle map uses, applied to one exercise's age. +function strengthFromAge(ageMs) { + if (!Number.isFinite(ageMs) || ageMs < 0) return STRENGTH_FLOOR + if (ageMs <= STRENGTH_FULL_MS) return 1 + return Math.max(STRENGTH_FLOOR, halfLifeDecay(ageMs - STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS)) +} + +// Timestamp of the exercise's latest completed WORK set (warm-ups excluded - they are prep, +// not stimulus, and the strength model is built on effective work). +function lastWorkSetAt(S, id) { + let latest = -Infinity + for (const workout of S?.workouts || []) { + const ts = workout.start || new Date(workout.d).getTime() + if (!Number.isFinite(ts) || ts <= latest) continue + const entry = (workout.entries || []).find(e => e.id === id) + if (!entry) continue + if ((entry.sets || []).some(s => s.done === true && !isWarmupRow(s))) latest = ts + } + return Number.isFinite(latest) ? latest : null +} + +function snapshotWeights(entry) { + const catalogue = entry && typeof entry === 'object' ? EXIDX[entry.id] : null + if (catalogue) { + const weights = musclesOf(catalogue) + if (Object.keys(weights).length) return weights + } + const direct = entry && typeof entry === 'object' + ? (entry.muscleWeights || entry.muscleSnapshot?.muscleWeights) + : null + if (direct && typeof direct === 'object' && !Array.isArray(direct) && Object.keys(direct).length) { + return direct + } + return musclesOf(entry) +} + +// Highest-weight muscle of an exercise - used for the primary/secondary badge and the +// per-muscle link, not for the decay (the exercise's own decay is what the row shows). +export function primaryMuscleOf(entry) { + const weights = snapshotWeights(entry) + let best = null + for (const [slug, weight] of Object.entries(weights)) { + if (!best || weight > best.weight) best = { slug, weight } + } + return best +} + +function exerciseName(entry) { + // Imported history often has no name snapshot (entries are { id, sets, topW }) - the + // catalogue (or the registered custom) is the canonical name source. + const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null + if (ex?.n) return ex.n + if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n + return entry && typeof entry === 'object' && entry.n ? entry.n : null +} + +function firstEntryWithId(S, id) { + for (const workout of S?.workouts || []) { + const entry = (workout.entries || []).find(e => e.id === id) + if (entry) return entry + } + return null +} + +/** + * Strength rows for every exercise with an estimate: best estimated 1RM (work sets only, + * warm-ups excluded), the estimate's date, the exercise's primary muscle, the exercise's + * OWN decay (from its last done work set), and the expected current 1RM (estimate x decay). + * Sorted by expected current 1RM, strongest first. Exercises without a usable estimate are + * omitted - a made-up number is worse than no number. + */ +export function strengthExerciseRows(S, now) { + const workouts = S?.workouts || [] + const ids = [...new Set(workouts.flatMap(w => (w.entries || []).map(e => e.id)))] + const rows = [] + for (const id of ids) { + const best = best1RM(S, id) + if (!best) continue + const entry = firstEntryWithId(S, id) + const lastAt = lastWorkSetAt(S, id) + const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt) + rows.push({ + id, + name: exerciseName(entry) || id, + est: best.est, + estDate: best.d, + primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null, + decay, + current: round1(best.est * decay), + }) + } + return rows.sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name))) +} + +/** + * Strength rows for the exercises whose logged snapshot includes `slug` (primary 1 / + * secondary 0.4 badge), each with the exercise's OWN decay and expected current 1RM - the + * tapped muscle filters the list, the row still speaks for the exercise. + */ +export function strengthExerciseRowsForMuscle(S, now, slug) { + const workouts = S?.workouts || [] + const seen = new Map() + for (const workout of workouts) { + for (const entry of workout.entries || []) { + if (seen.has(entry.id)) continue + const weights = snapshotWeights(entry) + const weight = weights[slug] + if (!weight) continue + const best = best1RM(S, entry.id) + if (!best) continue + const lastAt = lastWorkSetAt(S, entry.id) + const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt) + const primary = primaryMuscleOf(entry) + seen.set(entry.id, { + id: entry.id, + name: exerciseName(entry) || entry.id, + weight, + primary: primary ? primary.slug : null, + est: best.est, + estDate: best.d, + decay, + current: round1(best.est * decay), + }) + } + } + return [...seen.values()].sort((a, b) => b.current - a.current || String(a.name).localeCompare(String(b.name))) +} diff --git a/frontend/src/lib/strength-exercises.test.js b/frontend/src/lib/strength-exercises.test.js new file mode 100644 index 0000000..d765186 --- /dev/null +++ b/frontend/src/lib/strength-exercises.test.js @@ -0,0 +1,176 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { strengthExerciseRows, strengthExerciseRowsForMuscle, primaryMuscleOf } from './strength-exercises.js' +import { registerCustom } from './exercises.js' + +const DAY = 86400000 +const NOW = Date.UTC(2026, 7, 8, 12) // 2026-08-08 12:00 UTC + +const CUSTOMS = [ + { id: 'bench', n: 'Bench Press', tg: 'chest', mg: 'triceps', sm: ['deltoids'] }, + { id: 'squat', n: 'Squat', tg: 'quadriceps', mg: 'glutes' }, + { id: 'fly', n: 'Cable Crossovers', tg: 'deltoids', mg: 'chest' }, + { id: 'pushdown', n: 'Triceps Pushdown', tg: 'triceps' }, + { id: 'undone', n: 'Undone Lift', tg: 'upper-back' }, + { id: 'stretch', n: 'Chest Stretch', tg: 'chest' }, +] + +beforeEach(() => registerCustom(CUSTOMS)) +afterEach(() => registerCustom([])) + +function workout(dayAgo, entries) { + const d = new Date(NOW - dayAgo * DAY) + const iso = d.toISOString().slice(0, 10) + return { id: 'x' + iso, d: iso, start: NOW - dayAgo * DAY, unit: 'kg', entries } +} + +const bench = { id: 'bench', n: 'Bench Press', muscleWeights: { chest: 1, triceps: 0.4, deltoids: 0.4 }, sets: [ + { phase: 'warmup', w: 40, r: 8, done: true, unit: 'kg' }, + { phase: 'work', w: 80, r: 8, done: true, unit: 'kg' }, + { phase: 'work', w: 85, r: 6, done: true, unit: 'kg' }, +] } +// est 85x6 -> 102.0 ; 80x8 -> 101.3 ; warmup 40x8 -> 50.7 (must never win) + +const squat = { id: 'squat', n: 'Squat', muscleWeights: { quadriceps: 1, glutes: 0.4 }, sets: [ + { phase: 'work', w: 100, r: 5, done: true, unit: 'kg' }, +] } +// est 100x5 -> 116.7 ; trained 30 days ago -> quadriceps decayed (30d - 14d = 16d / 28d half-life) + +const fly = { id: 'fly', n: 'Cable Crossovers', muscleWeights: { chest: 0.4, deltoids: 1 }, sets: [ + { phase: 'work', w: 20, r: 12, done: true, unit: 'kg' }, +] } +// est 20x12 -> 28 ; chest is SECONDARY here + +const pushdown = { id: 'pushdown', n: 'Triceps Pushdown', muscleWeights: { triceps: 1 }, sets: [ + { phase: 'work', w: 30, r: 10, done: true, unit: 'kg' }, +] } +// est 30x10 -> 40 + +const undone = { id: 'undone', n: 'Undone Lift', muscleWeights: { 'upper-back': 1 }, sets: [ + { phase: 'work', w: 200, r: 5, done: false, unit: 'kg' }, +] } + +const noLoad = { id: 'stretch', n: 'Chest Stretch', muscleWeights: { chest: 0.4 }, sets: [ + { phase: 'work', w: 0, r: 10, done: true }, +] } + +const unitState = (workouts) => ({ unit: 'kg', workouts }) + +describe('strengthExerciseRows', () => { + it('lists every exercise with an estimate, warm-ups excluded, sorted by expected current 1RM', () => { + const S = unitState([ + workout(3, [bench]), + workout(30, [squat]), + workout(3, [fly, pushdown]), + workout(2, [undone, noLoad]), + ]) + const rows = strengthExerciseRows(S, NOW) + // undone (no completed set) and stretch (no load) have no estimate -> omitted + expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly', 'pushdown', 'squat']) + // strongest expected current first: bench 102 > squat ~78.5 > pushdown 40 > fly 28 + expect(rows[0].id).toBe('bench') + expect(rows.at(-1).id).toBe('fly') + }) + + it('keeps warm-up sets out of the estimate and reports the date of the best work set', () => { + const S = unitState([workout(3, [bench])]) + const rows = strengthExerciseRows(S, NOW) + expect(rows).toHaveLength(1) + expect(rows[0].est).toBe(102) // 85x6, not 80x8, not the 40x8 warm-up + expect(rows[0].estDate).toBe('2026-08-05') + expect(rows[0].primary).toBe('chest') + }) + + it('resolves real exercise names from the catalogue even when entries lack a name snapshot', () => { + // Imported history entries are { id, sets, topW } - no `n` snapshot. The catalogue + // (or the registered custom) must supply the display name, not the raw id. + const nameless = { id: 'bench', sets: bench.sets } // no n, no muscleWeights + const S = unitState([workout(3, [nameless])]) + const rows = strengthExerciseRows(S, NOW) + expect(rows).toHaveLength(1) + expect(rows[0].name).toBe('Bench Press') + expect(rows[0].id).toBe('bench') + const muscleRows = strengthExerciseRowsForMuscle(S, NOW, 'chest') + expect(muscleRows[0].name).toBe('Bench Press') + }) + + it('uses nested exercise snapshots for a deleted custom exercise', () => { + const deleted = { + id: 'deleted-custom', + muscleSnapshot: { n: 'Deleted custom', muscleWeights: { chest: 1 } }, + sets: [{ phase: 'work', warmup: true, w: 80, r: 8, done: true, unit: 'kg' }], + } + const S = unitState([workout(3, [deleted])]) + const rows = strengthExerciseRows(S, NOW) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ id: 'deleted-custom', name: 'Deleted custom', primary: 'chest', est: 101.3 }) + expect(strengthExerciseRowsForMuscle(S, NOW, 'chest')[0].name).toBe('Deleted custom') + }) + + it('applies the exercise own decay to the expected current 1RM', () => { + const S = unitState([workout(3, [bench]), workout(30, [squat])]) + const rows = strengthExerciseRows(S, NOW) + const benchRow = rows.find(r => r.id === 'bench') + const squatRow = rows.find(r => r.id === 'squat') + // bench last done 3 days ago -> still inside the 14-day full-retention plateau + expect(benchRow.decay).toBe(1) + expect(benchRow.current).toBe(102) + // squat last done 30 days ago -> 16 days past the plateau at a 28-day half-life + const squatDecay = 0.5 ** (16 / 28) + expect(squatRow.decay).toBeCloseTo(squatDecay, 4) + expect(squatRow.current).toBeCloseTo(Math.round(116.7 * squatDecay * 10) / 10, 2) + }) + + it('keeps the exercise own decay even when its muscle is kept fresh by other work', () => { + // bench last done 30 days ago, but chest is fresh (fly trained 3 days ago): the row + // speaks for the exercise, so bench still shows its own decline. + const S = unitState([workout(30, [bench]), workout(3, [fly])]) + const rows = strengthExerciseRows(S, NOW) + const benchRow = rows.find(r => r.id === 'bench') + const benchDecay = 0.5 ** (16 / 28) + expect(benchRow.decay).toBeCloseTo(benchDecay, 4) + expect(benchRow.current).toBeCloseTo(Math.round(102 * benchDecay * 10) / 10, 2) + }) +}) + +describe('strengthExerciseRowsForMuscle', () => { + it('lists primary and secondary exercises for the tapped muscle, with that muscle decay', () => { + const S = unitState([workout(3, [bench, fly, pushdown])]) + const rows = strengthExerciseRowsForMuscle(S, NOW, 'chest') + expect(rows.map(r => r.id).sort()).toEqual(['bench', 'fly']) + const benchRow = rows.find(r => r.id === 'bench') + const flyRow = rows.find(r => r.id === 'fly') + expect(benchRow.weight).toBe(1) + expect(benchRow.primary).toBe('chest') + expect(flyRow.weight).toBe(0.4) + expect(flyRow.primary).toBe('deltoids') + expect(flyRow.decay).toBe(1) // chest is at full retention + expect(flyRow.current).toBe(28) + }) + + it('the tapped muscle filters the list; the row decay stays the exercise own', () => { + const S = unitState([workout(3, [bench]), workout(30, [fly])]) + const rows = strengthExerciseRowsForMuscle(S, NOW, 'triceps') + const benchRow = rows.find(r => r.id === 'bench') + // bench trains triceps secondarily (0.4), so it appears under the tapped triceps - + // but the decay is bench's own (3 days ago -> full), not triceps' stale muscle value. + expect(benchRow.weight).toBe(0.4) + expect(benchRow.primary).toBe('chest') + expect(benchRow.decay).toBe(1) + expect(benchRow.current).toBe(102) + }) + + it('returns nothing for a muscle nothing trains', () => { + const S = unitState([workout(3, [bench])]) + expect(strengthExerciseRowsForMuscle(S, NOW, 'biceps')).toEqual([]) + }) +}) + +describe('primaryMuscleOf', () => { + it('prefers the catalogue, then the logged snapshot, and handles missing metadata', () => { + expect(primaryMuscleOf({ id: 'bench', muscleWeights: {} }).slug).toBe('chest') // catalogue wins + expect(primaryMuscleOf({ muscleWeights: { chest: 1, triceps: 0.4 } }).slug).toBe('chest') // snapshot fallback + expect(primaryMuscleOf({ tg: 'back', mg: 'biceps' }).slug).toBe('upper-back') // canonicalised + expect(primaryMuscleOf({})).toBeNull() + expect(primaryMuscleOf(null)).toBeNull() + }) +}) diff --git a/frontend/src/lib/workout-model.js b/frontend/src/lib/workout-model.js new file mode 100644 index 0000000..e296ee6 --- /dev/null +++ b/frontend/src/lib/workout-model.js @@ -0,0 +1,74 @@ +// Focused workout semantics shared by session, history, and strength views. +// Legacy records have no explicit phase or mode, so the defaults preserve main's work/reps shape. + +const MODES = ['reps', 'time', 'cardio'] +const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {} + +function normalizedPhase(value, fallback = 'work') { + const token = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (token === 'warmup' || token === 'warm-up' || token === 'warm_up') return 'warmup' + if (token === 'work') return 'work' + return fallback === 'warmup' ? 'warmup' : 'work' +} + +/** Resolve a row's phase. An explicit phase wins over the legacy warmup boolean. */ +export function phaseForSet(set, fallback = 'work') { + const source = objectOf(set) + if (source.phase != null && source.phase !== '') return normalizedPhase(source.phase, fallback) + return source.warmup === true ? 'warmup' : normalizedPhase(undefined, fallback) +} + +export function isWarmupRow(set) { + return phaseForSet(set) === 'warmup' +} + +export function normalizeMode(value, fallback = 'reps') { + const token = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (MODES.includes(token)) return token + return MODES.includes(fallback) ? fallback : 'reps' +} + +function modeFromUnit(value) { + const token = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (['rep', 'reps', 'repetition', 'repetitions'].includes(token)) return 'reps' + if (['sec', 'secs', 'second', 'seconds'].includes(token)) return 'time' + if (['min', 'mins', 'minute', 'minutes'].includes(token)) return 'cardio' + return null +} + +function explicitMode(source) { + const value = objectOf(source).mode + const token = typeof value === 'string' ? value.trim().toLowerCase() : '' + return MODES.includes(token) ? token : modeFromUnit(objectOf(source).unit) +} + +function inferredMode(source) { + const value = objectOf(source) + const explicit = explicitMode(value) + if (explicit) return explicit + if (String(value.mode || '').trim().toLowerCase() === 'amrap') return 'reps' + if (value.min != null || value.speed != null) return 'cardio' + if (value.sec != null || value.seconds != null || value.durationSec != null) return 'time' + if (value.r != null || value.reps != null || value.actualReps != null) return 'reps' + return null +} + +/** Resolve one row's mode: explicit row, parent target, then legacy result fields. */ +export function modeForSet(set, target = {}) { + return explicitMode(set) || inferredMode(target) || inferredMode(set) || 'reps' +} + +/** Resolve a single mode for an entry; mixed work-row modes intentionally return null. */ +export function modeForEntry(entry, fallback = null) { + const source = objectOf(entry) + const target = objectOf(source.target || source) + const sets = Array.isArray(source.sets) ? source.sets : [] + const work = sets.filter(set => !isWarmupRow(set)) + const observed = work.length ? work : sets + const modes = [...new Set(observed.map(set => modeForSet(set, target)))] + if (modes.length > 1) return null + if (modes.length === 1) return modes[0] + const targetMode = inferredMode(target) + if (targetMode) return targetMode + return fallback == null ? modeForSet(source, target) : normalizeMode(fallback) +} diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 14d2720..d0f6d36 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -14,12 +14,14 @@ import Icon from './components/Icon.jsx' import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx' import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js' import BodyMap from './components/BodyMap.jsx' -import { loadOfWorkouts } from './lib/muscles.js' +import { exerciseMuscleSnapshot, loadOfWorkouts } from './lib/muscles.js' import { parseImport, mergeImport } from './lib/import-csv.js' import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js' import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js' import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js' import { MOBILE, shareExport } from './lib/mobile.js' +import { buildCompletedWorkout } from './lib/finish-workout.js' +import { isWarmupRow } from './lib/workout-model.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -388,10 +390,15 @@ export function deleteCustomEx(ex, afterDelete) { confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { + // Keep display and muscle metadata in history before the custom catalogue row disappears. + const snapshot = exerciseMuscleSnapshot(ex) + s.workouts.forEach(w => w.entries.forEach(e => { + if (e.id !== ex.id) return + e.n = ex.n + if (!e.muscleSnapshot || !Object.keys(e.muscleSnapshot).length) e.muscleSnapshot = snapshot + })) s.customEx = (s.customEx || []).filter(x => x.id !== ex.id) s.routines.forEach(r => { r.ex = r.ex.filter(e => e.id !== ex.id); cleanupSg(r.ex) }) - // stamp the name into history entries so past workouts stay readable - s.workouts.forEach(w => w.entries.forEach(e => { if (e.id === ex.id) e.n = ex.n })) delete s.exWeights[ex.id] }) toast(t('Exercise deleted')) @@ -849,7 +856,7 @@ function TopWeight({ entryIdx, close }) { // to sit after every one of them. const entry = A ? A.entries[entryIdx] : null const ex = entry && EXIDX[entry.id] - const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)) : 0 + const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0 const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0 const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0) useEffect(() => { if (!entry) close() }, [!entry]) @@ -939,25 +946,22 @@ function doFinishWorkout() { const prs = [] const e1prs = [] A.entries.forEach(e => { - const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w)) + const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w)) if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id) // A heavier estimate without a heavier top set is its own kind of progress — // same weight for more reps. Reported separately so it can't be read as a load PR. const rec = is1RMRecord(st, e.id, e) if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec }) }) - const w = { - id: A.id, d: A.d, start: A.start, end: Date.now(), routineId: A.routineId, name: A.name, bw: A.bw, - // `target` (what the session prescribed) is kept alongside the sets: without it a - // finished workout cannot say whether it hit its reps, and a timed session reads back - // as "0 reps". It is what the progression engine works from. - entries: A.entries.map(e => ({ id: e.id, sets: e.sets, topW: e.topW || null, target: e.target || null })).filter(e => e.sets.some(s => s.done)), - prs - } + const w = buildCompletedWorkout(A, { + end: Date.now(), + prs, + snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null, + }) w.vol = workoutVolume(w) update(s => { w.entries.forEach(e => { - const mx = Math.max(0, ...e.sets.filter(x => x.done).map(x => x.w || 0), e.topW || 0) + const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0) if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } } }) s.workouts.push(w) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index af08fba..b2e5a26 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' import { EXIDX } from '../lib/exercises.js' -import { lastBW, streakWeeks, setLabel, modeOf, effortOf } from '../lib/history.js' +import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js' import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js' import { t } from '../lib/i18n.js' import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx' @@ -12,6 +12,7 @@ import Icon from '../components/Icon.jsx' import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx' import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js' import { fatigueOf, strengthOf, STRENGTH_FLOOR } from '../lib/recovery.js' +import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js' import { fatigueStateOf } from '../lib/recovery-view.js' import { e1rmSeries, best1RM } from '../lib/onerm.js' import { @@ -19,6 +20,7 @@ import { effortHistogram, isHardSet, HARD_RIR } from '../lib/effort.js' import { Button, Segmented, SelectRow } from '../components/ui.jsx' +import { isWarmupRow } from '../lib/workout-model.js' // Which muscles the training in a window actually hit — and, the point of the card, // which ones it keeps missing. Shading is relative within the window (lib/muscles.js). @@ -28,8 +30,9 @@ function latestMuscleTraining(workouts) { const timestamp = Number(workout?.start || new Date(workout?.d).getTime()) if (!Number.isFinite(timestamp)) continue for (const entry of workout.entries || []) { - if (!(entry.sets || []).some(set => set?.done === true)) continue - for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) { + if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue + const exercise = EXIDX[entry.id] || entry.exercise || entry + for (const slug of Object.keys(musclesOf(exercise))) { if (latest[slug] == null || timestamp > latest[slug]) latest[slug] = timestamp } } @@ -37,7 +40,7 @@ function latestMuscleTraining(workouts) { return latest } -const FATIGUE_LEVELS = [ +export const FATIGUE_LEVELS = [ { at: 0, level: 0 }, { at: 0.15, level: 1 }, { at: 0.25, level: 2 }, @@ -45,7 +48,7 @@ const FATIGUE_LEVELS = [ { at: 0.55, level: 4, exclusive: true }, ] -const STRENGTH_LEVELS = [ +export const STRENGTH_LEVELS = [ { at: STRENGTH_FLOOR, level: 0 }, { at: 0.625, level: 1 }, { at: 0.75, level: 2 }, @@ -100,11 +103,10 @@ function MuscleBalance({ S }) { const [sel, setSel] = useState(null) const now = useNow() const workouts = S.workouts - const fatigue = useMemo(() => fatigueOf(workouts, now), [workouts, now]) + const fatigue = useMemo(() => fatigueOf(workouts, now, { unit: S.unit }), [workouts, now, S.unit]) const strength = useMemo(() => strengthOf(workouts, now), [workouts, now]) + const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel]) const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts]) - const { worked: strengthOrder } = rankOf(strength) - const detrained = strengthOrder.filter(slug => strength[slug] < 1) const strengthHint = slug => { if (lastTrained[slug] == null) return t('not trained') const weeks = weeksSinceTraining(now, lastTrained[slug]) @@ -125,6 +127,8 @@ function MuscleBalance({ S }) { const volWin = S.workouts.filter(w => (w.start || new Date(w.d).getTime()) > now - 90 * 86400000) const vol90 = loadOfWorkouts(volWin, null) const { worked, missed } = rankOf(load) + const { worked: strengthOrder } = rankOf(strength) + const detrained = strengthOrder.filter(slug => strength[slug] < 1) const top = worked.slice(0, 4) const max = worked.length ? load[worked[0]] : 0 const sets = m => Math.round((load[m] || 0) * 10) / 10 @@ -176,6 +180,25 @@ function MuscleBalance({ S }) {
{t('Strength shows retained muscle strength. Train again to reset it.')}
+ {sel && <> +

{t('Exercises')} · {t(MUSCLE_NAME[sel])}

+ {muscleExercises.length ? muscleExercises.map(row => ( +
+ + + {row.name} + {row.primary === sel + ? {t('primary')} + : {t('secondary')}} + + {t('Est. 1RM')}: {fmtNum(row.est)} {S.unit} · {fmtDate(row.estDate, true)} + + + {fmtNum(row.current)} {S.unit} · {Math.round(row.decay * 100)}% +
+ )) :
{t('No exercises with an estimated 1RM yet.')}
} + } + {!sel &&
{t('Tap a muscle to see its exercises.')}
} {detrained.map(slug =>
{t(MUSCLE_NAME[slug])} @@ -185,6 +208,7 @@ function MuscleBalance({ S }) {
} + // How hard the training was — the half of the picture a volume chart cannot show. Everything // is computed in RIR (lib/effort.js) and converted to whichever scale this profile reads. // Every number carries how much of the training it speaks for: rating is optional and off by @@ -248,7 +272,6 @@ export default function Stats() { const [exId, setExId] = useState(null) const [exMetric, setExMetric] = useState('top') const now = Date.now() - const anyEffort = hasEffort(S) const kind = displayScale(S) const hd = scaleName(kind) @@ -256,31 +279,34 @@ export default function Stats() { .map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d })) const bw30 = S.bodyweight.filter(b => (b.t || new Date(b.d).getTime()) > now - 30 * 86400000) const bwDelta30 = bw30.length > 1 ? bw30[bw30.length - 1].w - bw30[0].w : null - const monthW = S.workouts.filter(w => w.d.slice(0, 7) === todayISO().slice(0, 7)).length + const workouts = S.workouts + const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length + const nameOf = id => EXIDX[id]?.n || workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id const currentOf = id => { - for (let i = S.workouts.length - 1; i >= 0; i--) { - const en = S.workouts[i].entries.find(e => e.id === id) + for (let i = workouts.length - 1; i >= 0; i--) { + const en = workouts[i].entries.find(e => e.id === id) if (!en) continue - const mode = modeOf({ ...(en.target || {}), id }) - const metric = s2 => mode === 'cardio' ? (s2.speed || 0) : mode === 'time' ? (s2.sec || 0) : (s2.w || 0) - const mx = Math.max(0, ...en.sets.filter(s2 => s2.done).map(metric), mode === 'time' || mode === 'cardio' ? 0 : (en.topW || 0)) + const mode = metricModeForEntry(en) || modeOf({ id }) + const rows = metricRowsForEntry(en, mode) + const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0))) if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit } } return { mx: 0, unit: S.unit } } - const exHist = [...new Set(S.workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id]) + const exHist = [...new Set(workouts.flatMap(w => w.entries.map(e => e.id)))].filter(id => EXIDX[id] || nameOf(id) !== id) const exCurrent = Object.fromEntries(exHist.map(id => [id, currentOf(id)])) - exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || (EXIDX[a].n < EXIDX[b].n ? -1 : 1)) - + exHist.sort((a, b) => exCurrent[b].mx - exCurrent[a].mx || nameOf(a).localeCompare(nameOf(b))) const curEx = exId && exHist.includes(exId) ? exId : exHist[0] || null - // How this exercise was logged most recently decides what the curve means: top weight, - // longest hold or top speed. Sets logged in another mode lack the field and score 0, so a - // switched exercise drops its old points instead of mixing seconds into a weight chart. + // A completed reps work row is authoritative for strength metrics, even when the parent + // target also contains timed/cardio work. Entries without reps rows use their selected mode. const curMode = curEx ? (() => { - for (let i = S.workouts.length - 1; i >= 0; i--) { - const en = S.workouts[i].entries.find(e => e.id === curEx) - if (en) return modeOf({ ...(en.target || {}), id: curEx }) + for (let i = workouts.length - 1; i >= 0; i--) { + const en = workouts[i].entries.find(e => e.id === curEx) + if (en) { + const mode = metricModeForEntry(en) + if (mode) return mode + } } return modeOf({ id: curEx }) })() : 'reps' @@ -290,16 +316,25 @@ export default function Stats() { const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unit let exPts = [], exList = [], exBest = 0 if (curEx) { - S.workouts.forEach(w => { + workouts.forEach(w => { const en = w.entries.find(e => e.id === curEx) - if (en) { const mx = Math.max(0, ...en.sets.filter(s => s.done).map(metric), curCardio || curTimed ? 0 : (en.topW || 0)); if (mx > 0) { exPts.push({ t: w.start, y: mx, d: w.d, sets: en.sets.filter(s => s.done), target: en.target }); if (mx > exBest) exBest = mx } } + if (en) { + const loggedMode = metricModeForEntry(en) + if (loggedMode !== curMode) return + const doneSets = metricRowsForEntry(en, curMode) + const mx = curMode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...doneSets.map(metric)) + if (mx > 0) { + exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target }) + if (mx > exBest) exBest = mx + } + } }) exList = exPts.slice(-5).reverse() } // Estimated 1RM (issue #18) — only reps-mode training produces one, so cardio and timed // work simply have no points and the toggle stays hidden. - const e1Pts = curEx ? e1rmSeries(S, curEx) : [] - const e1Best = curEx ? best1RM(S, curEx) : null + const e1Pts = curEx && curMode === 'reps' ? e1rmSeries(S, curEx) : [] + const e1Best = curEx && curMode === 'reps' ? best1RM(S, curEx) : null const showE1 = e1Pts.length > 0 // Effort on this exercise, per session. It rides on the top-set curve as well as having a // curve of its own, because the two only mean something together: the same weight moved @@ -324,19 +359,20 @@ export default function Stats() {
-
{t('Workouts')}
{S.workouts.length}
+
{t('Workouts')}
{workouts.length}
{t('This month')}
{monthW}
{t('Week streak')}
{streakWeeks(S)}
{t('Weight 30d')}
{bwDelta30 === null ? '—' : (bwDelta30 > 0 ? '+' : '') + fmtNum(bwDelta30) + ' ' + S.unit}
+

{t('Activity — last 12 months')} · {t('by time trained')}

- { const ws = S.workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} /> + { const ws = workouts.filter(w => w.d === iso); if (ws.length === 1) workoutDetailSheet(ws[0]); else if (ws.length) calendarSheet(iso) }} />
- {S.workouts.length > 0 && } - {anyEffort && } + {workouts.length > 0 && } + {hasEffort(S) && }
@@ -357,8 +393,7 @@ export default function Stats() { {exHist.length ? <>
({ value: id, label: EXIDX[id].n + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} /> - + options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
{exOpts.length > 1 && }
@@ -382,12 +417,12 @@ export default function Stats() {
- {S.workouts.length > 0 && <> + {workouts.length > 0 && <>

{t('Recent workouts')}

- +
-
{[...S.workouts].reverse().slice(0, 6).map(w => workoutDetailSheet(w)} />)}
+
{[...workouts].reverse().slice(0, 6).map(w => workoutDetailSheet(w)} />)}
} } From 4e842b00e1aa681327430892f69f43bef8e3f375 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 12 Aug 2026 20:20:34 +0200 Subject: [PATCH 46/58] feat: resolve warm-up rows by phase --- frontend/src/lib/effort.js | 3 +- frontend/src/lib/effort.test.js | 11 ++++ frontend/src/lib/history.js | 5 +- frontend/src/lib/history.test.js | 83 ++++++++++++++-------------- frontend/src/lib/import-csv.js | 10 ++-- frontend/src/lib/import-csv.test.js | 22 ++++++++ frontend/src/lib/muscles.js | 5 +- frontend/src/lib/muscles.test.js | 20 ++++++- frontend/src/lib/onerm.js | 3 +- frontend/src/lib/progression.js | 9 +-- frontend/src/lib/progression.test.js | 11 ++++ frontend/src/lib/workout-model.js | 22 ++++++++ frontend/src/sheets.jsx | 5 +- frontend/src/views/Workout.jsx | 12 ++-- 14 files changed, 156 insertions(+), 65 deletions(-) create mode 100644 frontend/src/lib/import-csv.test.js create mode 100644 frontend/src/lib/workout-model.js diff --git a/frontend/src/lib/effort.js b/frontend/src/lib/effort.js index 8865147..2417353 100644 --- a/frontend/src/lib/effort.js +++ b/frontend/src/lib/effort.js @@ -8,6 +8,7 @@ // floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2. import { EFFORT, effortOf } from './history.js' import { weekKey } from './format.js' +import { isWarmupRow } from './workout-model.js' // At or below this a set is close enough to failure to be the kind that drives adaptation. // 3 rather than 2: the line is a convention, and drawn one rep too generously it still @@ -44,7 +45,7 @@ export const scaleName = kind => EFFORT[kind].hd function eachDoneSet(S, fn) { ;(S.workouts || []).forEach(w => (w.entries || []).forEach(e => - (e.sets || []).forEach(s => { if (s.done && !s.warmup) fn(s, w, e) }))) + (e.sets || []).forEach(s => { if (s.done && !isWarmupRow(s)) fn(s, w, e) }))) } // A window in days, counted back from now. 0 = everything, which is also what an empty diff --git a/frontend/src/lib/effort.test.js b/frontend/src/lib/effort.test.js index b313f2e..8a5de70 100644 --- a/frontend/src/lib/effort.test.js +++ b/frontend/src/lib/effort.test.js @@ -116,6 +116,17 @@ describe('effortSummary', () => { it('survives a profile with no training at all', () => { expect(effortSummary({ workouts: [] }, 30)).toEqual({ done: 0, rated: 0, hard: 0, avg: null, hardPct: null }) }) + + it('uses phase as authoritative while retaining legacy boolean warm-up fallback', () => { + const summary = effortSummary(S(W(1, [ + { rir: 0, phase: 'warmup' }, + { rir: 1, phase: 'work', warmup: true }, + { rir: 2 }, { rir: 2 }, { rir: 2 }, { rir: 2 }, + ])), 0) + expect(summary.done).toBe(5) + expect(summary.rated).toBe(5) + expect(summary.hard).toBe(5) + }) }) describe('hasEffort', () => { diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index d261345..a32c3c3 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -1,6 +1,7 @@ // Pure helpers over the state object S (ported 1:1 from the vanilla app). import { todayISO, isoOf, weekKey, fmtNum } from './format.js' import { isCardio, isBodyweightEq } from './exercises.js' +import { isWarmupRow } from './workout-model.js' // i18n-core, not i18n: this file is imported by mcp/, which is plain Node with no Vite and no // React. i18n.js is the Vite half — import.meta.glob over the locale packs, useSyncExternalStore // for the hook — and it re-exports this very `t` from core, so nothing changes here except what @@ -330,7 +331,7 @@ export function streakWeeks(S) { * undone take the new value (null deletes the key). Done sets are never rewritten. */ export function cascadeWeight(rows, from, value) { - const warm = !!rows[from]?.warmup + const warm = isWarmupRow(rows[from]) const next = rows.slice() for (let j = from + 1; j < next.length; j++) { if (!!next[j].warmup === warm && !next[j].done) { @@ -343,7 +344,7 @@ export function cascadeWeight(rows, from, value) { /** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */ export function insertWarmupRow(rows, mode, target) { - const firstWork = rows.findIndex(x => !x.warmup) + const firstWork = rows.findIndex(x => !isWarmupRow(x)) const at = firstWork === -1 ? rows.length : firstWork const l = rows[at - 1] || rows[rows.length - 1] const warm = mode === 'cardio' diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index 68d1f0a..b264b89 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -9,49 +9,6 @@ const CARDIO = EXDB.find(e => e.bp === 'cardio').id const LIFT = EXDB.find(e => e.bp !== 'cardio' && e.eq !== 'body weight').id const BW = EXDB.find(e => e.eq === 'body weight').id -describe('superset editing', () => { - it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => { - const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] - - const paired = pairAdjacent(entries, 1, 2, 'sg-new') - - expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }]) - expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) - expect(supersetUnits(paired)).toEqual([[0], [1, 2]]) - }) - - it('merges both contiguous groups when their boundary entries are paired', () => { - const entries = [ - { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' }, - { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' } - ] - - const merged = pairAdjacent(entries, 1, 2) - - expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left']) - expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right']) - }) - - it('unpairs one entry and removes sg values left without an adjacent partner', () => { - const entries = [ - { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' }, - { id: 'd', sg: 'orphan' } - ] - - const unpaired = unpairSuperset(entries, 1) - - expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]) - expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan']) - }) - - it('rejects a non-adjacent pairing request', () => { - const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] - - expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/) - expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) - }) -}) - describe('modeOf', () => { it('falls back to the body part when a plan has no mode — every existing plan keeps working', () => { expect(modeOf({ id: CARDIO })).toBe('cardio') @@ -522,6 +479,46 @@ describe('workoutVolume', () => { }) }) +describe('superset editing', () => { + it('pairs adjacent entries without mutating the source and keeps the display units contiguous', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + const paired = pairAdjacent(entries, 1, 2, 'sg-new') + + expect(paired).toEqual([{ id: 'a' }, { id: 'b', sg: 'sg-new' }, { id: 'c', sg: 'sg-new' }]) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + expect(supersetUnits(paired)).toEqual([[0], [1, 2]]) + }) + + it('merges both contiguous groups when their boundary entries are paired', () => { + const entries = [ + { id: 'a', sg: 'left' }, { id: 'b', sg: 'left' }, + { id: 'c', sg: 'right' }, { id: 'd', sg: 'right' } + ] + const merged = pairAdjacent(entries, 1, 2) + + expect(merged.map(e => e.sg)).toEqual(['left', 'left', 'left', 'left']) + expect(entries.map(e => e.sg)).toEqual(['left', 'left', 'right', 'right']) + }) + + it('unpairs one entry and removes sg values left without an adjacent partner', () => { + const entries = [ + { id: 'a', sg: 'group' }, { id: 'b', sg: 'group' }, { id: 'c', sg: 'group' }, + { id: 'd', sg: 'orphan' } + ] + const unpaired = unpairSuperset(entries, 1) + + expect(unpaired).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }, { id: 'd' }]) + expect(entries.map(e => e.sg)).toEqual(['group', 'group', 'group', 'orphan']) + }) + + it('rejects a non-adjacent pairing request', () => { + const entries = [{ id: 'a' }, { id: 'b' }, { id: 'c' }] + + expect(() => pairAdjacent(entries, 0, 2, 'sg-invalid')).toThrow(/adjacent/) + expect(entries).toEqual([{ id: 'a' }, { id: 'b' }, { id: 'c' }]) + }) +}) + describe('session row helpers', () => { it('cascadeWeight propagates to same-flag undone rows and never rewrites done sets', () => { diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js index b09f984..73a9bd2 100644 --- a/frontend/src/lib/import-csv.js +++ b/frontend/src/lib/import-csv.js @@ -20,6 +20,7 @@ import { EXDB, EXIDX } from './exercises.js' import { uid } from './format.js' +import { isWarmupRow } from './workout-model.js' /* ----------------------------------------------------------------- CSV ---- */ @@ -345,7 +346,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) { ? num(cell(r, 'distanceKm')) : toKm(cell(r, 'distance'), cell(r, 'distanceUnit')) if (!w && !reps && !mins && !km) { skipped++; continue } - if (/warm/i.test(cell(r, 'setType'))) warmups++ + const warmup = /warm/i.test(cell(r, 'setType')) + if (warmup) warmups++ const key = keyOf(name) let id = resolved.get(key) @@ -368,8 +370,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) { // `u` carries the row's own unit into the conversion pass below and is dropped there — // it never reaches the stored set. const set = isCardio - ? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true } - : { w, r: reps || 0, done: true, u: rowUnit } + ? { min: mins || 0, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) } + : { w, r: reps || 0, done: true, u: rowUnit, ...(warmup ? { phase: 'warmup' } : {}) } // Effort rides along only where the app can show it again: a weighted rep set. A treadmill // row with an RPE would have nowhere to put it. A set is kept on one scale, so a file // carrying both columns is read as RIR — the same precedence setLabel reads them back with. @@ -416,7 +418,7 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) { const day = byDate.get(d) const entries = [...day.ex.entries()].map(([id, ss]) => { const conv2 = ss.map(({ u, ...s }) => (s.w !== undefined ? { ...s, w: convRow({ ...s, u }) } : s)) - const mx = Math.max(0, ...conv2.map(s => s.w || 0)) + const mx = Math.max(0, ...conv2.filter(s => !isWarmupRow(s)).map(s => s.w || 0)) return { id, sets: conv2, topW: mx || null } }) const base = new Date(d + 'T00:00:00').getTime() diff --git a/frontend/src/lib/import-csv.test.js b/frontend/src/lib/import-csv.test.js new file mode 100644 index 0000000..4a8b164 --- /dev/null +++ b/frontend/src/lib/import-csv.test.js @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { parseWorkoutCSV } from './import-csv.js' + +const CSV = [ + 'Date,Exercise,Weight,Reps,Set Type', + '2026-08-08,Bench Press,100,5,Warm-up', + '2026-08-08,Bench Press,80,5,Working', +].join('\n') + +describe('CSV warm-up provenance', () => { + it('retains the imported warm-up phase and excludes it from topW', () => { + const parsed = parseWorkoutCSV(CSV, { unit: 'kg' }) + const entry = parsed.workouts[0].entries[0] + + expect(parsed.warmups).toBe(1) + expect(entry.sets).toEqual([ + { w: 100, r: 5, done: true, phase: 'warmup' }, + { w: 80, r: 5, done: true }, + ]) + expect(entry.topW).toBe(80) + }) +}) \ No newline at end of file diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index 00927a2..871cfef 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -8,6 +8,7 @@ // ankles, "cardiovascular system") maps to null and is dropped rather than guessed at. import { EXIDX , smOf } from './exercises.js' +import { isWarmupRow } from './workout-model.js' // The muscles a map can shade, in head-to-toe order — also the order of any list // built from them, so "what am I neglecting" reads top-down like a body. @@ -108,7 +109,7 @@ export function loadOf(items) { */ export const loadOfWorkouts = (workouts, pick) => loadOf((workouts || []).flatMap(w => - (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup && (!pick || pick(s))).length })))) + (w.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length })))) /** Load a routine *would* produce, from its planned set counts. */ export const loadOfRoutine = routine => @@ -116,7 +117,7 @@ export const loadOfRoutine = routine => /** Load for a workout still in progress — the sets ticked so far. */ export const loadOfActive = active => - loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !s.warmup).length }))) + loadOf((active?.entries || []).map(e => ({ id: e.id, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length }))) /** * Shade buckets 0–4 per muscle. diff --git a/frontend/src/lib/muscles.test.js b/frontend/src/lib/muscles.test.js index 3cde02e..6423eec 100644 --- a/frontend/src/lib/muscles.test.js +++ b/frontend/src/lib/muscles.test.js @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { EXIDX, EXDB, smOf } from './exercises.js' -import { musclesOf } from './muscles.js' +import { loadOfWorkouts, musclesOf } from './muscles.js' // The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps // those aliases to the canonical body-map slugs and applies the 0.4 support weight. @@ -42,3 +42,21 @@ describe('catalogue secondary additions', () => { expect(musclesOf(raw)).toHaveProperty('deltoids') }) }) + + +describe('map load with warm-up phases', () => { + it('excludes warm-up sets from the by-sets-worked map', () => { + const w = { + id: 'w1', d: '2026-08-01', start: Date.UTC(2026, 7, 1, 10), unit: 'kg', + entries: [{ + id: '0025', + sets: [ + { done: true, phase: 'warmup', w: 20, r: 8 }, + { done: true, phase: 'work', w: 60, r: 8 }, + ], + }], + } + const load = loadOfWorkouts([w], null) + expect(load.chest).toBe(1) + }) +}) diff --git a/frontend/src/lib/onerm.js b/frontend/src/lib/onerm.js index c3a0b11..2602118 100644 --- a/frontend/src/lib/onerm.js +++ b/frontend/src/lib/onerm.js @@ -1,3 +1,4 @@ +import { isWarmupRow } from './workout-model.js' // Estimated one-rep max (issue #18). // // Deliberately knows nothing about the exercise database: an estimate needs a weight AND a @@ -44,7 +45,7 @@ export function estimate1RM(w, r, formula = DEFAULT_FORMULA) { export function bestSetOf(entry, formula = DEFAULT_FORMULA) { let best = null ;(entry?.sets || []).forEach(s => { - if (!s.done || s.warmup) return + if (!s.done || isWarmupRow(s)) return const est = estimate1RM(s.w, s.r, formula) if (est !== null && (!best || est > best.est)) best = { est, w: Number(s.w), r: Math.round(Number(s.r)) } }) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index aa613d0..d8f9df6 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -18,6 +18,7 @@ import { modeOf, repStep } from './history.js' import { EXIDX } from './exercises.js' +import { isWarmupRow } from './workout-model.js' export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time'] @@ -103,7 +104,7 @@ export function readSession(entry, fallback) { const mode = modeOf({ ...target, id: entry && entry.id }) // Warm-up rows are prep, not the session: one filtered read beats guarding every consumer // below (an undone warm-up otherwise poisons `ok` forever and its reps drag `low`/`count`). - const sets = ((entry && entry.sets) || []).filter(s => !s.warmup) + const sets = ((entry && entry.sets) || []).filter(s => !isWarmupRow(s)) const planned = target.sets || sets.length const enough = sets.length >= planned @@ -134,7 +135,7 @@ export function sessionsFor(S, exId, fallback) { const out = [] ;(S.workouts || []).forEach(w => { const entry = w.entries.find(e => e.id === exId) - if (entry && entry.sets.some(s => s.done && !s.warmup)) out.push({ d: w.d, ...readSession(entry, fallback) }) + if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) }) }) return out } @@ -255,7 +256,7 @@ export function applyPrescription(sets, p) { // Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to // the work rows only (a ticked warm-up falling through here would be the data-loss the // cascade fix removed, two files over). - if (s.done || s.warmup) return s + if (s.done || isWarmupRow(s)) return s const o = { ...s } if (p.weight != null) o.w = p.weight if (p.reps != null) o.r = p.reps @@ -265,7 +266,7 @@ export function applyPrescription(sets, p) { // A policy that decided on a set count gets to grow the list — bodyweight progression adds // a set where a barbell would have added a plate. Only ever upwards, and only by copying a // row that is already there: a session in progress must not lose a set it has logged. - const workRows = out.filter(s => !s.warmup) + const workRows = out.filter(s => !isWarmupRow(s)) if (p.sets > workRows.length) { // An all-warm-up entry has no work row to seed growth from - growing warm-up copies // would both invent work and never terminate the loop. Leave the entry untouched. diff --git a/frontend/src/lib/progression.test.js b/frontend/src/lib/progression.test.js index b1857fd..a0e741f 100644 --- a/frontend/src/lib/progression.test.js +++ b/frontend/src/lib/progression.test.js @@ -476,6 +476,17 @@ describe('warm-up rows in session reads (round 3)', () => { expect(s.held).toEqual([45, 30]) expect(s.ok).toBe(false) // the 30s work row is the miss, not the warm-up }) + + it('uses phase as authoritative and falls back to the legacy warm-up flag', () => { + const s = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [ + { phase: 'warmup', w: 120, r: 20, done: true }, + { phase: 'work', warmup: true, w: 60, r: 5, done: true }, + ] }) + expect(s.count).toBe(1) + expect(s.weight).toBe(60) + expect(s.low).toBe(5) + expect(s.ok).toBe(true) + }) }) describe('applyPrescription never touches warm-up rows (round 3)', () => { diff --git a/frontend/src/lib/workout-model.js b/frontend/src/lib/workout-model.js new file mode 100644 index 0000000..ce293c3 --- /dev/null +++ b/frontend/src/lib/workout-model.js @@ -0,0 +1,22 @@ +// Focused workout semantics shared by session, history, and strength views. +// Legacy records have no explicit phase or mode, so the defaults preserve main's work/reps shape. + +const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {} + +function normalizedPhase(value, fallback = 'work') { + const token = typeof value === 'string' ? value.trim().toLowerCase() : '' + if (token === 'warmup' || token === 'warm-up' || token === 'warm_up') return 'warmup' + if (token === 'work') return 'work' + return fallback === 'warmup' ? 'warmup' : 'work' +} + +/** Resolve a row's phase. An explicit phase wins over the legacy warmup boolean. */ +export function phaseForSet(set, fallback = 'work') { + const source = objectOf(set) + if (source.phase != null && source.phase !== '') return normalizedPhase(source.phase, fallback) + return source.warmup === true ? 'warmup' : normalizedPhase(undefined, fallback) +} + +export function isWarmupRow(set) { + return phaseForSet(set) === 'warmup' +} \ No newline at end of file diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 14d2720..37ee6b7 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -20,6 +20,7 @@ import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-sha import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js' import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js' import { MOBILE, shareExport } from './lib/mobile.js' +import { isWarmupRow } from './lib/workout-model.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -849,7 +850,7 @@ function TopWeight({ entryIdx, close }) { // to sit after every one of them. const entry = A ? A.entries[entryIdx] : null const ex = entry && EXIDX[entry.id] - const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done).map(s => s.w || 0)) : 0 + const maxSet = entry ? Math.max(0, ...entry.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w || 0)) : 0 const prevBest = entry ? Math.max((st.exWeights[entry.id] || {}).w || 0, bestWeightFor(st, entry.id)) : 0 const [v, setV] = useState(entry ? (Math.max(maxSet, prevBest) || entry.target.weight || 0) : 0) useEffect(() => { if (!entry) close() }, [!entry]) @@ -939,7 +940,7 @@ function doFinishWorkout() { const prs = [] const e1prs = [] A.entries.forEach(e => { - const mx = Math.max(0, ...e.sets.filter(s => s.done).map(s => s.w)) + const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w)) if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id) // A heavier estimate without a heavier top set is its own kind of progress — // same weight for more reps. Reported separately so it can't be read as a load PR. diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 94d7be9..bc977b2 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -14,6 +14,7 @@ import Icon from '../components/Icon.jsx' import { Button, Check, NumberField } from '../components/ui.jsx' import { nextPrescription, applyPrescription } from '../lib/progression.js' import { glyphOf } from '../lib/glyphs.js' +import { isWarmupRow } from '../lib/workout-model.js' /* ---------- start chooser (no active workout) ---------- */ function StartChooser() { @@ -136,13 +137,14 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov {/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
{col1.hd}{col2 && {col2.hd}}{col3 && {col3.hd}}{timed && }
{entry.sets.map((s, i) => { - const warmBefore = i > 0 && !!entry.sets[i - 1].warmup - const isFirstWarmup = !!s.warmup && !warmBefore + const warm = isWarmupRow(s) + const warmBefore = i > 0 && isWarmupRow(entry.sets[i - 1]) + const isFirstWarmup = warm && !warmBefore // Numbering restarts per phase: with two warm-ups the first work set reads 1, not 3. - const phaseNum = entry.sets.slice(0, i + 1).filter(x => (x.warmup === true) === (s.warmup === true)).length + const phaseNum = entry.sets.slice(0, i + 1).filter(x => isWarmupRow(x) === warm).length return
{isFirstWarmup &&
{t('Warm-up')}
} - {!s.warmup && warmBefore &&
} + {!warm && warmBefore &&
}
{phaseNum}
{cell(s, i, col1, 'w')} @@ -152,7 +154,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov set off itself. The checkbox stays for anyone who timed it on their own watch. */} {timed && } - {s.warmup && } onToggle(i)} />
From 011a3f7790badee741195f651e1733a8e2461f28 Mon Sep 17 00:00:00 2001 From: Georgiy Sitnikov Date: Fri, 14 Aug 2026 11:28:09 +0200 Subject: [PATCH 47/58] Add healthcheck to Dockerfiles for API and web services --- api/Dockerfile | 8 ++++++++ web/Dockerfile | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/api/Dockerfile b/api/Dockerfile index ee69c8a..b3b7672 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -3,6 +3,14 @@ WORKDIR /app COPY package.json package-lock.json* ./ RUN npm install --omit=dev && npm cache clean --force COPY server.js ./ + ENV NODE_ENV=production +ENV PORT=3000 + EXPOSE 3000 CMD ["node", "server.js"] + +HEALTHCHECK --interval=5m \ + --timeout=5s \ + --retries=3 \ + CMD wget --spider -q http://localhost:${PORT}/api/config \ No newline at end of file diff --git a/web/Dockerfile b/web/Dockerfile index 9b30e63..aa33b8c 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -18,3 +18,8 @@ FROM nginx:alpine COPY web/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/dist /usr/share/nginx/html # exercise media (img/gif) is mounted at runtime from the media volume + +HEALTHCHECK --interval=5m \ + --timeout=5s \ + --retries=3 \ + CMD curl -fs http://localhost/ From 0e00e1029c5d5a34b18ce3999604bd0b1163e65f Mon Sep 17 00:00:00 2001 From: Georgiy Sitnikov Date: Fri, 14 Aug 2026 11:29:23 +0200 Subject: [PATCH 48/58] Add version metadata and update Dockerfile labels for API and web services --- .github/workflows/docker-publish.yml | 11 +++++++++++ api/Dockerfile | 22 +++++++++++++++++++--- web/Dockerfile | 22 +++++++++++++++++++--- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 602284f..b65f734 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -29,6 +29,13 @@ jobs: id: repo run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT" + - name: Set version metadata + id: version_meta + run: | + echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + echo "VCS_REF=${GITHUB_SHA}" >> $GITHUB_OUTPUT + echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT + - uses: docker/setup-qemu-action@v4 - uses: docker/setup-buildx-action@v4 @@ -52,6 +59,10 @@ jobs: context: ${{ matrix.context }} file: ${{ matrix.file }} platforms: linux/amd64,linux/arm64 + build-args: | + VERSION=${{ steps.version_meta.outputs.VERSION }} + VCS_REF=${{ steps.version_meta.outputs.VCS_REF }} + BUILD_DATE=${{ steps.version_meta.outputs.BUILD_DATE }} push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} diff --git a/api/Dockerfile b/api/Dockerfile index b3b7672..0276fe9 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -1,4 +1,20 @@ FROM node:22-alpine + +ARG VERSION=dev +ARG VCS_REF=dev +ARG BUILD_DATE=unknown + +LABEL maintainer="Duarte Santos https://github.com/DuarteSantos8" \ + org.opencontainers.image.title="opengym-api" \ + org.opencontainers.image.description="Backend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \ + org.opencontainers.image.source="https://github.com/DuarteSantos8/openGym" \ + org.opencontainers.image.url="http://ghcr.io/duartesantos8/opengym-api" \ + org.opencontainers.image.documentation="https://github.com/DuarteSantos8/openGym#" \ + org.opencontainers.image.licenses="AGPL-3.0 license" \ + org.opencontainers.image.version=$VERSION \ + org.opencontainers.image.revision=$VCS_REF \ + org.opencontainers.image.created=$BUILD_DATE + WORKDIR /app COPY package.json package-lock.json* ./ RUN npm install --omit=dev && npm cache clean --force @@ -11,6 +27,6 @@ EXPOSE 3000 CMD ["node", "server.js"] HEALTHCHECK --interval=5m \ - --timeout=5s \ - --retries=3 \ - CMD wget --spider -q http://localhost:${PORT}/api/config \ No newline at end of file + --timeout=5s \ + --retries=3 \ + CMD wget --spider -q http://localhost:${PORT}/api/config \ No newline at end of file diff --git a/web/Dockerfile b/web/Dockerfile index aa33b8c..96ed2d0 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -15,11 +15,27 @@ COPY frontend/ ./ RUN npm run build FROM nginx:alpine + +ARG VERSION=dev +ARG VCS_REF=dev +ARG BUILD_DATE=unknown + +LABEL maintainer="Duarte Santos https://github.com/DuarteSantos8" \ + org.opencontainers.image.title="opengym-web" \ + org.opencontainers.image.description="Frontend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \ + org.opencontainers.image.source="https://github.com/DuarteSantos8/openGym" \ + org.opencontainers.image.url="http://ghcr.io/duartesantos8/opengym-web" \ + org.opencontainers.image.documentation="https://github.com/DuarteSantos8/openGym#" \ + org.opencontainers.image.licenses="AGPL-3.0 license" \ + org.opencontainers.image.version=$VERSION \ + org.opencontainers.image.revision=$VCS_REF \ + org.opencontainers.image.created=$BUILD_DATE + COPY web/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/dist /usr/share/nginx/html # exercise media (img/gif) is mounted at runtime from the media volume HEALTHCHECK --interval=5m \ - --timeout=5s \ - --retries=3 \ - CMD curl -fs http://localhost/ + --timeout=5s \ + --retries=3 \ + CMD curl -fs http://localhost/ \ No newline at end of file From 1ba378b632adecb16e85cf5f6eb7088208708409 Mon Sep 17 00:00:00 2001 From: Georgiy Sitnikov Date: Fri, 14 Aug 2026 12:11:38 +0200 Subject: [PATCH 49/58] - Enable Templating feature as per https://hub.docker.com/_/nginx#using-environment-variables-in-nginx-configuration-new-in-119 - Set default Variables Solution for https://github.com/DuarteSantos8/openGym/issues/99 --- README.md | 3 +++ web/Dockerfile | 8 +++++++- web/{nginx.conf => nginx.conf.template} | 4 ++-- 3 files changed, 12 insertions(+), 3 deletions(-) rename web/{nginx.conf => nginx.conf.template} (94%) diff --git a/README.md b/README.md index 4da510b..7afbf24 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,9 @@ All via `.env` (see `.env.example`): | `RP_ID` | Hostname passkeys are bound to | `localhost` | | `ORIGIN` | Full URL the app is served from | `http://localhost:8080` | | `WEB_PORT` | Host port for the web UI | `8080` | +| `NGINX_PORT` | Internal Nginx port for the web UI | `80` | +| `BACKEND` | Backend Service service name, so that API calls can be forwarded to | `api` | +| `PORT` | Port for the api backend Service | `3000` | | `RP_NAME` | Name shown in the passkey prompt | `openGym` | | `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* | | `INVITE_ONLY` | Require an invite code to create a profile | *(off)* | diff --git a/web/Dockerfile b/web/Dockerfile index 9b30e63..ba21610 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -15,6 +15,12 @@ COPY frontend/ ./ RUN npm run build FROM nginx:alpine -COPY web/nginx.conf /etc/nginx/conf.d/default.conf +COPY web/nginx.conf.template /etc/nginx/templates/default.conf.template COPY --from=build /app/dist /usr/share/nginx/html # exercise media (img/gif) is mounted at runtime from the media volume + +# Set Default ENVs for nginx +ENV NGINX_PORT=80 +ENV BACKEND=api +ENV PORT=3000 + diff --git a/web/nginx.conf b/web/nginx.conf.template similarity index 94% rename from web/nginx.conf rename to web/nginx.conf.template index 505c16f..f8d67e6 100644 --- a/web/nginx.conf +++ b/web/nginx.conf.template @@ -1,13 +1,13 @@ # openGym — standalone web server: serves the static app AND proxies /api to the backend, # so the whole app lives on ONE origin (required for WebAuthn / passkeys). server { - listen 80; + listen ${NGINX_PORT}; root /usr/share/nginx/html; index index.html; # API → backend container location /api/ { - proxy_pass http://api:3000; + proxy_pass http://${BACKEND}:${PORT}; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; From 274a0276e0898111772f75b1f3345e40d5830f44 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:31:53 +0200 Subject: [PATCH 50/58] Release v1.2.6: Changelog-Datum auf den letzten Stand, Android zieht mit --- CHANGELOG.md | 2 +- frontend/android/app/build.gradle | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 124762c..76d8c71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v1.2.6 — 2026-08-07 +## v1.2.6 — 2026-08-11 The muscle map learned to answer a second question — not just where the volume went, but what is still recovering from it. Plus: a freestyle session no longer starts from blanks, the rest timer diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle index 0b58287..2ac4cc1 100644 --- a/frontend/android/app/build.gradle +++ b/frontend/android/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "ch.duartesantos.opengym" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 6 - versionName "1.2.5" + versionCode 7 + versionName "1.2.6" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. From 5d7e13361cb705dfbb22d4ff7bd2470bb3c28f84 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:38:37 +0200 Subject: [PATCH 51/58] Website: Download-Zeile auf die v1.2.6-APK --- website/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/index.html b/website/index.html index 052d86c..9c567ed 100644 --- a/website/index.html +++ b/website/index.html @@ -126,7 +126,7 @@
  • No cross-device sync
  • Download for Android -

    v1.2.4 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)

    +

    v1.2.6 · 4.3 MB · Android 6.0+ · signed APK, sideload (your browser will ask — that's normal outside the Play Store)

    iPhone? Apple doesn't allow installs outside the App Store — use the self-hosted version as a home-screen app instead, or see the docs.

    From 329eed4ce0b0907d6cb392db560828613509c419 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:39:26 +0200 Subject: [PATCH 52/58] CI: Images nur noch aus einem publizierten Release, nicht aus jedem Tag (#87) --- .github/workflows/docker-publish.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 602284f..b609db6 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -1,9 +1,14 @@ name: Publish Docker images +# Images are published from a *published release*, never from a bare tag push. +# A tag that is later deleted (the versioning rule consolidates unreleased tags) +# would otherwise leave its image tags behind in GHCR forever, and dependency +# bots read those as a newer version. See issue #87. on: push: branches: [main] - tags: ['v*'] + release: + types: [published] workflow_dispatch: permissions: From 55de70ad2301595044db9882b0536925740edd3b Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:44:24 +0200 Subject: [PATCH 53/58] i18n: neue Keys auf den Quote-Stil der Packs ziehen --- frontend/src/locales/de.js | 8 ++++---- frontend/src/locales/es.js | 8 ++++---- frontend/src/locales/fr.js | 6 +++--- frontend/src/locales/hi.js | 8 ++++---- frontend/src/locales/it.js | 8 ++++---- frontend/src/locales/ko.js | 8 ++++---- frontend/src/locales/pl.js | 8 ++++---- frontend/src/locales/pt.js | 8 ++++---- frontend/src/locales/ru.js | 8 ++++---- frontend/src/locales/tr.js | 8 ++++---- frontend/src/locales/zh.js | 8 ++++---- 11 files changed, 43 insertions(+), 43 deletions(-) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index 9c06d2b..d454b61 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -586,9 +586,9 @@ export default { '{0} sets · {1} work': '{0} Sätze · {1} Arbeit', 'Make superset with previous': 'Mit vorheriger Übung kombinieren', 'Make superset with next': 'Mit nächster Übung kombinieren', - "primary": "primär", - "secondary": "sekundär", - "No exercises with an estimated 1RM yet.": "Noch keine Übungen mit geschätztem 1RM.", - "Tap a muscle to see its exercises.": "Tippe auf einen Muskel, um seine Übungen zu sehen.", + 'primary': 'primär', + 'secondary': 'sekundär', + 'No exercises with an estimated 1RM yet.': 'Noch keine Übungen mit geschätztem 1RM.', + 'Tap a muscle to see its exercises.': 'Tippe auf einen Muskel, um seine Übungen zu sehen.', 'Unpair': 'Trennen' } diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index ab2875e..9d088d5 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} series · {1} trabajo', 'Make superset with previous': 'Hacer superserie con anterior', 'Make superset with next': 'Hacer superserie con siguiente', - "primary": "principal", - "secondary": "secundario", - "No exercises with an estimated 1RM yet.": "Aún no hay ejercicios con 1RM estimado.", - "Tap a muscle to see its exercises.": "Toca un músculo para ver sus ejercicios.", + 'primary': 'principal', + 'secondary': 'secundario', + 'No exercises with an estimated 1RM yet.': 'Aún no hay ejercicios con 1RM estimado.', + 'Tap a muscle to see its exercises.': 'Toca un músculo para ver sus ejercicios.', 'Unpair': 'Desvincular' } diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 3d9e293..c60aa35 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} séries · {1} travail', 'Make superset with previous': 'Faire un superset avec le précédent', 'Make superset with next': 'Faire un superset avec le suivant', - "primary": "principal", - "secondary": "secondaire", + 'primary': 'principal', + 'secondary': 'secondaire', "No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.", - "Tap a muscle to see its exercises.": "Touchez un muscle pour voir ses exercices.", + 'Tap a muscle to see its exercises.': 'Touchez un muscle pour voir ses exercices.', 'Unpair': 'Dissocier' } diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index c166031..47e1c29 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} सेट · {1} काम', 'Make superset with previous': 'पिछले के साथ सुपरसेट', 'Make superset with next': 'अगले के साथ सुपरसेट', - "primary": "प्राथमिक", - "secondary": "द्वितीयक", - "No exercises with an estimated 1RM yet.": "अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।", - "Tap a muscle to see its exercises.": "व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।", + 'primary': 'प्राथमिक', + 'secondary': 'द्वितीयक', + 'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।', + 'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।', 'Unpair': 'अलग करें' } diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index e5c9c77..0fd580b 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} serie · {1} lavoro', 'Make superset with previous': 'Superset con il precedente', 'Make superset with next': 'Superset con il successivo', - "primary": "primario", - "secondary": "secondario", - "No exercises with an estimated 1RM yet.": "Nessun esercizio con 1RM stimato finora.", - "Tap a muscle to see its exercises.": "Tocca un muscolo per vedere i suoi esercizi.", + 'primary': 'primario', + 'secondary': 'secondario', + 'No exercises with an estimated 1RM yet.': 'Nessun esercizio con 1RM stimato finora.', + 'Tap a muscle to see its exercises.': 'Tocca un muscolo per vedere i suoi esercizi.', 'Unpair': 'Separa' } diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 028440f..7400666 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} 세트 · {1} 작업', 'Make superset with previous': '이전 운동과 슈퍼셋', 'Make superset with next': '다음 운동과 슈퍼셋', - "primary": "주동", - "secondary": "보조", - "No exercises with an estimated 1RM yet.": "추정 1RM이 있는 운동이 아직 없습니다.", - "Tap a muscle to see its exercises.": "근육을 눌러 해당 운동을 확인하세요.", + 'primary': '주동', + 'secondary': '보조', + 'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.', + 'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.', 'Unpair': '분리' } diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index b4f437b..446f3f8 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} serii · {1} praca', 'Make superset with previous': 'Połącz z poprzednim', 'Make superset with next': 'Połącz z następnym', - "primary": "główny", - "secondary": "drugorzędny", - "No exercises with an estimated 1RM yet.": "Brak ćwiczeń z oszacowanym 1RM.", - "Tap a muscle to see its exercises.": "Dotknij mięśnia, aby zobaczyć jego ćwiczenia.", + 'primary': 'główny', + 'secondary': 'drugorzędny', + 'No exercises with an estimated 1RM yet.': 'Brak ćwiczeń z oszacowanym 1RM.', + 'Tap a muscle to see its exercises.': 'Dotknij mięśnia, aby zobaczyć jego ćwiczenia.', 'Unpair': 'Rozłącz' } diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 148ed63..503d952 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} séries · {1} trabalho', 'Make superset with previous': 'Fazer superset com o anterior', 'Make superset with next': 'Fazer superset com o próximo', - "primary": "primário", - "secondary": "secundário", - "No exercises with an estimated 1RM yet.": "Ainda não há exercícios com 1RM estimado.", - "Tap a muscle to see its exercises.": "Toque num músculo para ver os seus exercícios.", + 'primary': 'primário', + 'secondary': 'secundário', + 'No exercises with an estimated 1RM yet.': 'Ainda não há exercícios com 1RM estimado.', + 'Tap a muscle to see its exercises.': 'Toque num músculo para ver os seus exercícios.', 'Unpair': 'Desfazer' } diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 7893621..d1a1b93 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} подходов · {1} рабочих', 'Make superset with previous': 'Суперсет с предыдущим', 'Make superset with next': 'Суперсет со следующим', - "primary": "основная", - "secondary": "вспомогательная", - "No exercises with an estimated 1RM yet.": "Пока нет упражнений с расчётным 1ПМ.", - "Tap a muscle to see its exercises.": "Нажмите на мышцу, чтобы увидеть её упражнения.", + 'primary': 'основная', + 'secondary': 'вспомогательная', + 'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.', + 'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.', 'Unpair': 'Разъединить' } diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index e9839ac..ee195d2 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} set · {1} çalışma', 'Make superset with previous': 'Öncekiyle superset yap', 'Make superset with next': 'Sonrakiyle superset yap', - "primary": "birincil", - "secondary": "ikincil", - "No exercises with an estimated 1RM yet.": "Henüz tahmini 1RM olan egzersiz yok.", - "Tap a muscle to see its exercises.": "Egzersizlerini görmek için bir kas seçin.", + 'primary': 'birincil', + 'secondary': 'ikincil', + 'No exercises with an estimated 1RM yet.': 'Henüz tahmini 1RM olan egzersiz yok.', + 'Tap a muscle to see its exercises.': 'Egzersizlerini görmek için bir kas seçin.', 'Unpair': 'Ayır' } diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index f01c212..37ce378 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -569,9 +569,9 @@ export default { '{0} sets · {1} work': '{0} 组 · {1} 工作', 'Make superset with previous': '与上一个组成超级组', 'Make superset with next': '与下一个组成超级组', - "primary": "主要", - "secondary": "次要", - "No exercises with an estimated 1RM yet.": "暂无估算1RM的动作。", - "Tap a muscle to see its exercises.": "点击肌肉查看其动作。", + 'primary': '主要', + 'secondary': '次要', + 'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。', + 'Tap a muscle to see its exercises.': '点击肌肉查看其动作。', 'Unpair': '取消组合' } From 09baee49a7dea4c0a7f3e720acd81ba67e9b1bd9 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:54:55 +0200 Subject: [PATCH 54/58] Fatigue: linkedom bleibt (Modals-Test braucht es), Monotonie-Probe laeuft in CI --- .github/workflows/test.yml | 4 + frontend/package-lock.json | 270 +++++++++++++++++++++++++++++++++++++ frontend/package.json | 1 + 3 files changed, 275 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e8632b4..c0f2b2e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -43,6 +43,10 @@ jobs: working-directory: frontend - run: node scripts/check-locales.mjs working-directory: frontend + # The fatigue model must never read higher after a rest day than before it. + # Property probe over ~108k comparisons; too slow for the unit suite, cheap here. + - run: npm run test:fatigue-probe + working-directory: frontend mcp: runs-on: ubuntu-latest diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d923859..c693161 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -25,6 +25,7 @@ "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", "happy-dom": "^20.11.2", + "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" } @@ -2625,6 +2626,12 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/cssom": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", + "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", + "dev": true + }, "node_modules/dargs": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", @@ -3400,6 +3407,98 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", "dev": true }, + "node_modules/html-escaper": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz", + "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==", + "dev": true + }, + "node_modules/htmlparser2": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", + "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", + "dev": true, + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "entities": "^7.0.1" + } + }, + "node_modules/htmlparser2/node_modules/dom-serializer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", + "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", + "dev": true, + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/domhandler": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", + "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", + "dev": true, + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/domutils": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", + "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", + "dev": true, + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -3889,6 +3988,171 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/linkedom": { + "version": "0.18.13", + "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.13.tgz", + "integrity": "sha512-ES/o9qotMpzpN2MHs+Iq/JcVoOj8Fa5wiQYrTdFpvAnwXL0g66XHHUc9WUMk6nAlBtGsFQ24ne+SYnvnaQ2FSw==", + "dev": true, + "dependencies": { + "css-select": "^7.0.0", + "cssom": "^0.5.0", + "html-escaper": "^3.0.3", + "htmlparser2": "^10.1.0", + "uhyphen": "^0.2.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "canvas": ">= 2" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/linkedom/node_modules/boolbase": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz", + "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==", + "dev": true, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/css-select": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz", + "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==", + "dev": true, + "dependencies": { + "boolbase": "^2.0.0", + "css-what": "^8.0.0", + "domhandler": "^6.0.1", + "domutils": "^4.0.2", + "nth-check": "^3.0.1" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/css-what": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz", + "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==", + "dev": true, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/linkedom/node_modules/dom-serializer": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz", + "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==", + "dev": true, + "dependencies": { + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0", + "entities": "^8.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/domelementtype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz", + "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/linkedom/node_modules/domhandler": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz", + "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==", + "dev": true, + "dependencies": { + "domelementtype": "^3.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/domutils": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz", + "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==", + "dev": true, + "dependencies": { + "dom-serializer": "^3.0.0", + "domelementtype": "^3.0.0", + "domhandler": "^6.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/entities": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz", + "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==", + "dev": true, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/linkedom/node_modules/nth-check": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz", + "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==", + "dev": true, + "dependencies": { + "boolbase": "^2.0.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, "node_modules/load-json-file": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", @@ -5949,6 +6213,12 @@ "node": ">=0.8.0" } }, + "node_modules/uhyphen": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz", + "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==", + "dev": true + }, "node_modules/undici-types": { "version": "8.3.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index adb365e..42aa3f9 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -30,6 +30,7 @@ "@capacitor/ios": "^7.6.8", "@vitejs/plugin-react": "^6.0.3", "happy-dom": "^20.11.2", + "linkedom": "^0.18.13", "vite": "^8.1.5", "vitest": "^4.1.10" } From 55b9dcb864ef3071e8afaa3278ffabf2b49d162c Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 11:57:40 +0200 Subject: [PATCH 55/58] Warm-up: die vier verbliebenen Roh-Lesungen von .warmup ueber isWarmupRow, mit Regressionstests --- frontend/src/lib/history.js | 4 ++-- frontend/src/lib/history.test.js | 24 +++++++++++++++++++++++- frontend/src/lib/progression.js | 2 +- frontend/src/lib/recovery.js | 3 ++- 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js index a32c3c3..a39b199 100644 --- a/frontend/src/lib/history.js +++ b/frontend/src/lib/history.js @@ -334,7 +334,7 @@ export function cascadeWeight(rows, from, value) { const warm = isWarmupRow(rows[from]) const next = rows.slice() for (let j = from + 1; j < next.length; j++) { - if (!!next[j].warmup === warm && !next[j].done) { + if (isWarmupRow(next[j]) === warm && !next[j].done) { if (value == null) delete next[j].w else next[j].w = value } @@ -368,6 +368,6 @@ export function removeRowAt(rows, i) { /** Completed non-warm-up sets across a workout's entries. */ export function workSetsDone(w) { return (w?.entries || []).reduce( - (n, e) => n + (e.sets || []).filter(s => s.done && !s.warmup).length, 0, + (n, e) => n + (e.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0, ) } diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js index b264b89..650eada 100644 --- a/frontend/src/lib/history.test.js +++ b/frontend/src/lib/history.test.js @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits } from './history.js' +import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, supersetUnits, workSetsDone } from './history.js' import { EXDB } from './exercises.js' // Real ids out of the shipped catalogue, so the body-part fallback is exercised for real. @@ -569,3 +569,25 @@ describe('session row helpers', () => { expect(next[0].w).toBe(70) }) }) + +// The importer writes `phase: 'warmup'` and no `warmup` boolean (import-csv.js), so anything +// reading the raw flag counts an imported warm-up as work. Read through the model instead. +describe('warm-up rows identified by phase alone', () => { + const imported = { w: 40, r: 10, done: true, phase: 'warmup' } + const work = { w: 100, r: 5, done: true } + + it('workSetsDone does not count a phase-only warm-up', () => { + expect(workSetsDone({ entries: [{ sets: [imported, work] }] })).toBe(1) + }) + + it('cascadeWeight keeps phase-only warm-ups in their own lane', () => { + const rows = [ + { w: 40, r: 10, phase: 'warmup' }, + { w: 45, r: 10, phase: 'warmup' }, + { w: 100, r: 5 }, + ] + const next = cascadeWeight(rows, 0, 50) + expect(next[1].w).toBe(50) + expect(next[2].w).toBe(100) + }) +}) diff --git a/frontend/src/lib/progression.js b/frontend/src/lib/progression.js index d8f9df6..8248df7 100644 --- a/frontend/src/lib/progression.js +++ b/frontend/src/lib/progression.js @@ -272,7 +272,7 @@ export function applyPrescription(sets, p) { // would both invent work and never terminate the loop. Leave the entry untouched. if (!workRows.length) return out const seed = workRows[workRows.length - 1] - while (out.filter(s => !s.warmup).length < p.sets) out.push({ ...seed, done: false }) + while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false }) } return out } diff --git a/frontend/src/lib/recovery.js b/frontend/src/lib/recovery.js index 5d63f00..373786e 100644 --- a/frontend/src/lib/recovery.js +++ b/frontend/src/lib/recovery.js @@ -1,5 +1,6 @@ import { EXIDX } from './exercises.js' import { MUSCLES, musclesOf } from './muscles.js' +import { isWarmupRow } from './workout-model.js' // A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve // 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting @@ -303,7 +304,7 @@ export function strengthOf(workouts, now, opts = {}) { const timestamp = workoutTimestamp(workout) if (!Number.isFinite(timestamp)) continue for (const entry of workout.entries || []) { - if (!(entry.sets || []).some(set => set?.done === true && !set?.warmup)) continue + if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) { if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) { latest[slug] = timestamp From 3b720b0332ebbf157168303ccea0b27080c7116a Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 12:03:31 +0200 Subject: [PATCH 56/58] Remove-Exercise: Randfaelle abgedeckt (letzte Uebung, Zweier-Superset, cur unterhalb) --- frontend/src/views/Workout.remove.test.jsx | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/frontend/src/views/Workout.remove.test.jsx b/frontend/src/views/Workout.remove.test.jsx index 1243c39..77516cb 100644 --- a/frontend/src/views/Workout.remove.test.jsx +++ b/frontend/src/views/Workout.remove.test.jsx @@ -117,3 +117,30 @@ describe('remove-exercise locale coverage', () => { }) }) }) + +describe('remove-exercise edge cases', () => { + it('removing the last remaining exercise leaves an empty, coherent session', () => { + setActive([entry('a')], 0) + act(() => { removeActiveExercise(0) }) + const A = useStore.getState().S.active + expect(A.entries).toHaveLength(0) + expect(A.cur).toBe(0) + }) + + it('removing one half of a two-member superset dissolves the group', () => { + setActive([entry('a', 'g1'), entry('b', 'g1'), entry('c')], 0) + act(() => { removeActiveExercise(1) }) + const A = useStore.getState().S.active + expect(A.entries.map(e => e.id)).toEqual(['a', 'c']) + // A superset of one is not a superset. + expect(A.entries[0].sg).toBeUndefined() + }) + + it('removing an entry below the active one keeps cur on the same exercise', () => { + setActive([entry('a'), entry('b'), entry('c')], 2) + act(() => { removeActiveExercise(0) }) + const A = useStore.getState().S.active + expect(A.entries.map(e => e.id)).toEqual(['b', 'c']) + expect(A.entries[A.cur].id).toBe('c') + }) +}) From c17632ea3dd175eb100315a4431146d3abd4dcf3 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 12:08:15 +0200 Subject: [PATCH 57/58] Superset-Flow: High-Water-Marken nach dem Entfernen einer Uebung neu setzen, api.js im Test gemockt --- frontend/src/views/Workout.jsx | 6 +++++ frontend/src/views/Workout.test.jsx | 39 +++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 606168e..7b9f61a 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -201,6 +201,12 @@ function ActiveWorkout() { // next exercise in the group, then back up to the first exercise of the next round. const exRefs = useRef({}) const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length)) + // The marks are index-keyed, and removing an exercise shifts every index above it down + // (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a + // shifted exercise inherits its predecessor's mark and its real progress reads as a re-check. + useEffect(() => { + progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length) + }, [A.entries.length]) useEffect(() => { if (!isSuperset) return const el = exRefs.current[cur] diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index 9794b7e..1c7282e 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -48,6 +48,12 @@ vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn(), })) vi.mock('../components/Media.jsx', () => ({ default: () => null })) +// api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the +// tests rather than declaring a vitest environment, so it must not depend on an ambient one. +vi.mock('../lib/api.js', () => ({ + api: vi.fn(() => Promise.resolve({})), + IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics', +})) let dom let root @@ -144,3 +150,36 @@ describe('Workout set completion flow', () => { expect(mocks.startRest).toHaveBeenCalledWith(90) }) }) + +describe('superset flow survives an exercise being removed mid-session', () => { + // removeActiveExercise splices A.entries, shifting every index above the removal down. + // The high-water marks are index-keyed, so without re-baselining the shifted exercise + // inherits its predecessor's mark and its next completed set reads as an uncheck/re-check + // — no advance, and no rest at the end of the round. + it('still advances and rests for sets completed after a removal', async () => { + // warm(2 sets, both done) ahead of a bench/row superset with nothing done yet. + await mount([ + exercise('warm', [true, true]), + exercise('bench', [false, false], { sg: 'g1' }), + exercise('row', [false, false], { sg: 'g1' }), + ], 1) + + // Drop the first exercise: bench moves 1 -> 0, row moves 2 -> 1. + // Stale marks would be [2, 0, 0] against entries that are now [bench, row]. + await act(async () => { + mocks.S.active.entries.splice(0, 1) + mocks.S.active.cur = 0 + root.render(React.createElement(Workout)) + }) + mocks.startRest.mockClear() + + // First member of the group: real progress, so the flow advances to the partner. + await toggleSet(0) + await act(async () => { root.render(React.createElement(Workout)) }) + expect(mocks.S.active.cur).toBe(1) + + // Partner closes the round (each still has a second set), which is what starts the rest. + await toggleSet(2) + expect(mocks.startRest).toHaveBeenCalledWith(90) + }) +}) From 5bf149e60bc1ec69a8c3aae3357a63dd2213979d Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Tue, 18 Aug 2026 12:11:51 +0200 Subject: [PATCH 58/58] i18n: Checker fuer Quell-Strings, die in KEINEM Pack stehen (check-locales sieht die nicht) --- .github/workflows/test.yml | 5 ++ frontend/scripts/check-source-strings.mjs | 69 +++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 frontend/scripts/check-source-strings.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c0f2b2e..58acb9a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -43,6 +43,11 @@ jobs: working-directory: frontend - run: node scripts/check-locales.mjs working-directory: frontend + # check-locales compares the packs to each other, so a key missing from ALL of them is + # invisible to it. This walks src/ instead. Report-only for now: there is a known + # backlog of untranslated demo-view strings to clear before it can fail the build. + - run: node scripts/check-source-strings.mjs + working-directory: frontend # The fatigue model must never read higher after a rest day than before it. # Property probe over ~108k comparisons; too slow for the unit suite, cheap here. - run: npm run test:fatigue-probe diff --git a/frontend/scripts/check-source-strings.mjs b/frontend/scripts/check-source-strings.mjs new file mode 100644 index 0000000..75202a5 --- /dev/null +++ b/frontend/scripts/check-source-strings.mjs @@ -0,0 +1,69 @@ +#!/usr/bin/env node +// The companion to check-locales.mjs, which compares the locale packs to each other and so +// cannot see a key that is missing from all of them: that renders English in every language +// while every check stays green. This walks src/ instead, collects the literals actually +// passed to t(), and reports the ones no pack defines. +// +// node scripts/check-source-strings.mjs # report only, exit 0 +// node scripts/check-source-strings.mjs --strict # exit 1 if anything is missing +// +// English is the source language and has no pack, so the key IS the English string. +// Only literal single-argument calls are collected — t(variable) and template literals are +// resolved at runtime and are deliberately out of scope. + +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { dirname, join, relative } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const root = join(dirname(fileURLToPath(import.meta.url)), '..') +const srcDir = join(root, 'src') +const localesDir = join(srcDir, 'locales') +const strict = process.argv.includes('--strict') + +function walk(dir, out = []) { + for (const name of readdirSync(dir)) { + const p = join(dir, name) + if (statSync(p).isDirectory()) { + if (p === localesDir || name === 'instr' || name === 'node_modules') continue + walk(p, out) + } else if (/\.(js|jsx)$/.test(name) && !/\.test\.(js|jsx)$/.test(name)) { + out.push(p) + } + } + return out +} + +// t('literal') / t("literal") — preceded by a non-identifier char so DateTimeFormat( misses. +const CALL = /(^|[^A-Za-z0-9_$.])t\(\s*(['"])((?:\\.|(?!\2)[^\\])*)\2/g + +const used = new Map() +for (const file of walk(srcDir)) { + const text = readFileSync(file, 'utf8') + for (const m of text.matchAll(CALL)) { + const key = m[3].replace(/\\(['"\\])/g, '$1') + if (!key) continue + if (!used.has(key)) used.set(key, new Set()) + used.get(key).add(relative(root, file)) + } +} + +const defined = new Set() +for (const file of readdirSync(localesDir).filter(f => f.endsWith('.js'))) { + const pack = (await import(pathToFileURL(join(localesDir, file)).href)).default + for (const key of Object.keys(pack)) defined.add(key) +} + +const missing = [...used.keys()].filter(k => !defined.has(k)).sort() + +if (!missing.length) { + console.log(`${used.size} translated strings in src/, all present in the locale packs.`) + process.exit(0) +} + +console.log(`${used.size} translated strings in src/, ${missing.length} defined in no locale pack:\n`) +for (const key of missing) { + console.log(` ${JSON.stringify(key)}`) + for (const f of [...used.get(key)].sort()) console.log(` ${f}`) +} +console.log(`\nThese render English in all ${readdirSync(localesDir).filter(f => f.endsWith('.js')).length} translated languages.`) +process.exit(strict ? 1 : 0)