@trainheroic-unofficial/js 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
1
+ import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
+ import { z } from "zod";
2
3
  export * from "@trainheroic-unofficial/dto";
3
4
  //#region src/auth.ts
4
5
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
@@ -1770,97 +1771,458 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
1770
1771
  };
1771
1772
  }
1772
1773
  //#endregion
1773
- //#region src/coach.ts
1774
- const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
1775
- /** Normalize one-or-many emails into a deduped, trimmed list. */
1776
- function emailList(emails) {
1777
- return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1778
- }
1779
- /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
1780
- function rosterName(rec) {
1781
- const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
1782
- if (full !== "") return full;
1783
- const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
1784
- return combined !== "" ? combined : null;
1774
+ //#region src/workout-encode.ts
1775
+ const LEADERBOARD_TYPE = {
1776
+ completion: 0,
1777
+ "for completion": 0,
1778
+ weight: 1,
1779
+ lb: 1,
1780
+ load: 1,
1781
+ reps: 2,
1782
+ rep: 2,
1783
+ rounds: 3,
1784
+ round: 3,
1785
+ time: 4,
1786
+ yards: 5,
1787
+ yd: 5,
1788
+ meters: 6,
1789
+ m: 6,
1790
+ feet: 7,
1791
+ ft: 7,
1792
+ calories: 8,
1793
+ cal: 8,
1794
+ cals: 8,
1795
+ miles: 10,
1796
+ mi: 10,
1797
+ inches: 12,
1798
+ in: 12,
1799
+ watts: 15,
1800
+ w: 15,
1801
+ velocity: 17,
1802
+ "m/s": 17,
1803
+ seconds: 18,
1804
+ sec: 18,
1805
+ s: 18
1806
+ };
1807
+ const LEADERBOARD_LABEL = {
1808
+ 0: "For Completion",
1809
+ 1: "Weight",
1810
+ 2: "Reps",
1811
+ 3: "Rounds",
1812
+ 4: "Time",
1813
+ 5: "Yards",
1814
+ 6: "Meters",
1815
+ 7: "Feet",
1816
+ 8: "Calories",
1817
+ 10: "Miles",
1818
+ 12: "Inches",
1819
+ 13: "Other",
1820
+ 15: "Watts",
1821
+ 16: "Percent",
1822
+ 17: "Velocity",
1823
+ 18: "Seconds"
1824
+ };
1825
+ function resolveLeaderboard(block) {
1826
+ const lb = block.leaderboard;
1827
+ if (lb === void 0 || lb === null) return {
1828
+ isRedzone: null,
1829
+ redzoneType: 0,
1830
+ smallerIsBetter: null,
1831
+ redzoneInstruction: ""
1832
+ };
1833
+ let unit;
1834
+ let instruction = "";
1835
+ let lowest;
1836
+ if (typeof lb === "object") {
1837
+ unit = lb.unit ?? lb.type;
1838
+ instruction = lb.instruction ?? "";
1839
+ lowest = lb.lowest_wins;
1840
+ } else unit = lb;
1841
+ let rz;
1842
+ if (typeof unit === "string") {
1843
+ const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
1844
+ if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
1845
+ rz = found;
1846
+ } else if (typeof unit === "number") rz = Math.trunc(unit);
1847
+ else throw new Error("Leaderboard requires a unit.");
1848
+ if (lowest === void 0) lowest = rz === 4 || rz === 18;
1849
+ return {
1850
+ isRedzone: 1,
1851
+ redzoneType: rz,
1852
+ smallerIsBetter: lowest ? 1 : 0,
1853
+ redzoneInstruction: instruction
1854
+ };
1785
1855
  }
1786
- /**
1787
- * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
1788
- * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
1789
- * and the warehouse store map the roster identically. Includes the account owner and
1790
- * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
1791
- */
1792
- async function fetchCoachRoster(client, ids) {
1793
- const res = await client.request("GET", "/v5/athletes");
1794
- if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1795
- const keep = ids && ids.length > 0 ? new Set(ids) : null;
1856
+ function slots(values, n = 10) {
1796
1857
  const out = [];
1797
- for (const row of res.data) {
1798
- if (typeof row !== "object" || row === null) continue;
1799
- const rec = row;
1800
- const id = coerceInt(rec.id);
1801
- if (id === null || id <= 0) continue;
1802
- if (keep && !keep.has(id)) continue;
1803
- out.push({
1804
- id,
1805
- name: rosterName(rec)
1806
- });
1807
- }
1858
+ for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
1808
1859
  return out;
1809
1860
  }
1861
+ function repsList(ex) {
1862
+ const reps = ex.reps;
1863
+ if (Array.isArray(reps)) return reps.map((r) => String(r));
1864
+ if (reps === void 0 || reps === null) return [];
1865
+ const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
1866
+ return Array.from({ length: sets }, () => String(reps));
1867
+ }
1868
+ /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
1869
+ function makeExercise(ex, workoutSetId, order, key) {
1870
+ const reps = repsList(ex);
1871
+ let instruction = ex.instr ?? "";
1872
+ if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
1873
+ const hasWeight = ex.weight !== void 0 && ex.weight !== null;
1874
+ const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
1875
+ let count = reps.length;
1876
+ if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
1877
+ let param2Type;
1878
+ let param2Values;
1879
+ if (hasWeight) {
1880
+ param2Type = ex.param_2_type ?? 1;
1881
+ param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
1882
+ } else {
1883
+ param2Type = 0;
1884
+ param2Values = null;
1885
+ }
1886
+ const entry = {
1887
+ exercise_id: ex.id,
1888
+ workout_set_id: workoutSetId,
1889
+ set_id: workoutSetId,
1890
+ setKey: workoutSetId,
1891
+ title: ex.title ?? "",
1892
+ instruction,
1893
+ order,
1894
+ param_1_type: ex.param_1_type ?? 3,
1895
+ param_2_type: param2Type,
1896
+ workout_set_exercise_template_id: null,
1897
+ no_sets: 0,
1898
+ param_count: count,
1899
+ set_num: count,
1900
+ key,
1901
+ video_url: "",
1902
+ thumbnail_url: "",
1903
+ tags: [],
1904
+ eType: "e",
1905
+ use_count: 0
1906
+ };
1907
+ const p1 = slots(reps);
1908
+ const p2 = slots(param2Values);
1909
+ for (let i = 0; i < 10; i += 1) {
1910
+ entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
1911
+ entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
1912
+ }
1913
+ return entry;
1914
+ }
1915
+ /** Block `type` values the coach calendar accepts (verified in workout-creation.md). */
1916
+ const BLOCK_TYPE_CONDITIONING = 1;
1917
+ const BLOCK_TYPE_HYPERTROPHY = 2;
1810
1918
  /**
1811
- * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1812
- * addresses (`POST /v5/emails/validate`), then invite the validated ones
1813
- * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
1919
+ * Default block type: text-only (empty exercises) blocks are Conditioning / Circuit (type 1);
1920
+ * structured exercise blocks default to Hypertrophy (type 2). An explicit `type` always wins.
1814
1921
  */
1815
- async function inviteAthletes(client, args) {
1816
- const list = emailList(args.emails);
1817
- if (list.length === 0) throw new Error("Provide at least one email address to invite.");
1818
- const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1819
- if (!validation.ok) {
1820
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1821
- throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1822
- }
1823
- const valid = Array.isArray(validation.data) ? validation.data : list;
1824
- if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1825
- const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1826
- teamType: 0,
1827
- teamId: args.teamId,
1828
- orgId: null,
1829
- emails: valid,
1830
- message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1831
- } });
1832
- if (!invite.ok) {
1833
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1834
- throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1922
+ function defaultBlockType(block) {
1923
+ if (block.type !== void 0) return block.type;
1924
+ return block.exercises.length === 0 ? 1 : 2;
1925
+ }
1926
+ function buildBlockPayload(blocks, workoutId) {
1927
+ return blocks.map((b, i) => {
1928
+ const lb = resolveLeaderboard(b);
1929
+ return {
1930
+ workout_id: workoutId,
1931
+ order: i + 1,
1932
+ type: defaultBlockType(b),
1933
+ instruction: b.instruction ?? "",
1934
+ is_redzone: lb.isRedzone,
1935
+ redzone_type: lb.redzoneType,
1936
+ smaller_is_better: lb.smallerIsBetter,
1937
+ redzone_instruction: lb.redzoneInstruction,
1938
+ exercises: [],
1939
+ exerciseKeys: [],
1940
+ key: `k::${workoutId}${i + 1}`,
1941
+ title: b.title
1942
+ };
1943
+ });
1944
+ }
1945
+ function unitOr(t) {
1946
+ return unitLabel(t) ?? "?";
1947
+ }
1948
+ /** Flag spec params the API will silently override to the exercise's fixed units. */
1949
+ function unitAdvisory(blockTitle, ex, defaults) {
1950
+ const notes = [];
1951
+ const warnings = [];
1952
+ const u = unitOr;
1953
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
1954
+ if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
1955
+ const sentP1 = ex.param_1_type;
1956
+ if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
1957
+ const sp1 = Math.trunc(Number(sentP1));
1958
+ warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
1959
+ } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
1960
+ if (ex.weight !== void 0 && ex.weight !== null) {
1961
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
1962
+ const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
1963
+ if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
1964
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
1835
1965
  }
1836
1966
  return {
1837
- teamId: args.teamId,
1838
- invited: valid,
1839
- result: invite.data
1967
+ notes,
1968
+ warnings
1840
1969
  };
1841
1970
  }
1842
1971
  /**
1843
- * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1844
- * The API wants the target date as a structured object (with weekday and an isToday flag),
1845
- * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
1972
+ * Run unit advisories across a whole block list against an exercise index. Shared by the
1973
+ * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
1974
+ * index is loaded first, otherwise `defaults` returns null on a cold index and every
1975
+ * advisory is silently dropped.
1846
1976
  */
1847
- async function copySession(client, args) {
1848
- const [year, month, day] = parseWorkoutDate(args.toDate);
1849
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1850
- const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1851
- const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1852
- toProgramId: args.toProgramId,
1853
- pwId: args.pwId,
1854
- toDate: {
1855
- date: iso,
1856
- day,
1857
- month,
1858
- year,
1859
- dayOfWeek,
1977
+ async function collectAdvisories(blocks, index) {
1978
+ await index.ensureFresh();
1979
+ const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
1980
+ block: b,
1981
+ ex
1982
+ })));
1983
+ const defaults = await Promise.all(pairs.map((p) => {
1984
+ const id = Number(p.ex.id);
1985
+ return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
1986
+ }));
1987
+ const notes = [];
1988
+ const warnings = [];
1989
+ pairs.forEach((p, i) => {
1990
+ const def = defaults[i];
1991
+ if (!def) return;
1992
+ const advisory = unitAdvisory(p.block.title, p.ex, def);
1993
+ notes.push(...advisory.notes);
1994
+ warnings.push(...advisory.warnings);
1995
+ });
1996
+ return {
1997
+ notes,
1998
+ warnings
1999
+ };
2000
+ }
2001
+ //#endregion
2002
+ //#region src/workout-session.ts
2003
+ /**
2004
+ * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2005
+ * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
2006
+ * `copySession` so the hint stays in one place.
2007
+ */
2008
+ function calendarWriteError(method, path, status, detail) {
2009
+ const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2010
+ if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2011
+ return /* @__PURE__ */ new Error(`${base}. This often means the program is another athlete's Coach Plan / personal calendar (personal_cal), which the coach calendar write endpoints do not support — workout_build and session_copy work on team/group programs (and the coach's own personal calendar), but there is currently no coach-facing tool to create sessions on another athlete's personal calendar.`);
2012
+ }
2013
+ async function req(client, method, path, body) {
2014
+ const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2015
+ if (!res.ok) {
2016
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2017
+ throw calendarWriteError(method, path, res.status, detail);
2018
+ }
2019
+ return res.data;
2020
+ }
2021
+ function createPath(opts) {
2022
+ if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2023
+ if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2024
+ const [y, m, d] = opts.date;
2025
+ return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2026
+ }
2027
+ async function buildSession(client, opts) {
2028
+ const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2029
+ const sess = await req(client, "POST", createPath(opts), {});
2030
+ checkResponse(sessionCreateResponseSchema, sess, "session create");
2031
+ const workoutId = Number(sess.workout_id);
2032
+ const pwId = Number(sess.id);
2033
+ const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2034
+ const byOrder = new Map(created.map((b) => [b.order, b.id]));
2035
+ let counter = 0;
2036
+ const payloads = blocks.map((block, i) => {
2037
+ const wsid = byOrder.get(i + 1);
2038
+ if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2039
+ return block.exercises.map((ex, j) => {
2040
+ counter += 1;
2041
+ return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2042
+ });
2043
+ });
2044
+ await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2045
+ if (opts.instruction !== void 0 && opts.instruction !== "") {
2046
+ const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2047
+ await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2048
+ }
2049
+ if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2050
+ return {
2051
+ pwId,
2052
+ workoutId
2053
+ };
2054
+ }
2055
+ /**
2056
+ * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2057
+ * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2058
+ * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2059
+ * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2060
+ */
2061
+ async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2062
+ const body = {
2063
+ ...pw,
2064
+ instruction,
2065
+ sets: blockIds,
2066
+ setKeys: blockIds
2067
+ };
2068
+ await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2069
+ }
2070
+ async function removeSession(client, programId, pwId) {
2071
+ await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2072
+ programId,
2073
+ pwId
2074
+ });
2075
+ }
2076
+ async function publishSession(client, pwId) {
2077
+ await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2078
+ }
2079
+ function str$1(value) {
2080
+ return value === void 0 || value === null ? "" : String(value);
2081
+ }
2082
+ async function readSession(client, programId, date, pwId) {
2083
+ const [y, m, d] = date;
2084
+ const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2085
+ checkResponse(programsEditResponseSchema, data, "programs edit");
2086
+ const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2087
+ if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2088
+ const setsObj = pw.sets ?? {};
2089
+ const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2090
+ return {
2091
+ pwId,
2092
+ date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
2093
+ published: pw.published,
2094
+ instruction: str$1(pw.instruction),
2095
+ blocks
2096
+ };
2097
+ }
2098
+ function readBlock(b) {
2099
+ const rz = coerceInt(b.redzone_type);
2100
+ let leaderboard = null;
2101
+ if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2102
+ const exercises = (Array.isArray(b.exercises) ? b.exercises : []).filter((ex) => coerceInt(ex.id) !== null || str$1(ex.title) !== "").sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2103
+ return {
2104
+ order: Number(b.order),
2105
+ title: str$1(b.title),
2106
+ instruction: str$1(b.instruction),
2107
+ leaderboard,
2108
+ exercises
2109
+ };
2110
+ }
2111
+ function readExercise(ex) {
2112
+ const reps = [];
2113
+ const load = [];
2114
+ for (let i = 1; i <= 10; i += 1) {
2115
+ const r = str$1(ex[`param_1_data_${i}`]);
2116
+ if (r !== "") reps.push(r);
2117
+ const w = str$1(ex[`param_2_data_${i}`]);
2118
+ if (w !== "") load.push(w);
2119
+ }
2120
+ return {
2121
+ order: Number(ex.order),
2122
+ title: str$1(ex.title),
2123
+ reps,
2124
+ primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2125
+ load,
2126
+ loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2127
+ instruction: str$1(ex.instruction)
2128
+ };
2129
+ }
2130
+ //#endregion
2131
+ //#region src/coach.ts
2132
+ const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
2133
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
2134
+ function emailList(emails) {
2135
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2136
+ }
2137
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2138
+ function rosterName(rec) {
2139
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2140
+ if (full !== "") return full;
2141
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2142
+ return combined !== "" ? combined : null;
2143
+ }
2144
+ /**
2145
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2146
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2147
+ * and the warehouse store map the roster identically. Includes the account owner and
2148
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2149
+ */
2150
+ async function fetchCoachRoster(client, ids) {
2151
+ const res = await client.request("GET", "/v5/athletes");
2152
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2153
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
2154
+ const out = [];
2155
+ for (const row of res.data) {
2156
+ if (typeof row !== "object" || row === null) continue;
2157
+ const rec = row;
2158
+ const id = coerceInt(rec.id);
2159
+ if (id === null || id <= 0) continue;
2160
+ if (keep && !keep.has(id)) continue;
2161
+ out.push({
2162
+ id,
2163
+ name: rosterName(rec)
2164
+ });
2165
+ }
2166
+ return out;
2167
+ }
2168
+ /**
2169
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2170
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
2171
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2172
+ */
2173
+ async function inviteAthletes(client, args) {
2174
+ const list = emailList(args.emails);
2175
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2176
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2177
+ if (!validation.ok) {
2178
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2179
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2180
+ }
2181
+ const valid = Array.isArray(validation.data) ? validation.data : list;
2182
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2183
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2184
+ teamType: 0,
2185
+ teamId: args.teamId,
2186
+ orgId: null,
2187
+ emails: valid,
2188
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2189
+ } });
2190
+ if (!invite.ok) {
2191
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2192
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2193
+ }
2194
+ return {
2195
+ teamId: args.teamId,
2196
+ invited: valid,
2197
+ result: invite.data
2198
+ };
2199
+ }
2200
+ /**
2201
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2202
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
2203
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2204
+ */
2205
+ async function copySession(client, args) {
2206
+ const [year, month, day] = parseWorkoutDate(args.toDate);
2207
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2208
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2209
+ const path = "/2.0/coach/calendar/copyProgramWorkout";
2210
+ const res = await client.request("POST", path, { body: {
2211
+ toProgramId: args.toProgramId,
2212
+ pwId: args.pwId,
2213
+ toDate: {
2214
+ date: iso,
2215
+ day,
2216
+ month,
2217
+ year,
2218
+ dayOfWeek,
1860
2219
  isToday: false
1861
2220
  }
1862
2221
  } });
1863
- if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
2222
+ if (!res.ok) {
2223
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2224
+ throw calendarWriteError("POST", path, res.status, detail);
2225
+ }
1864
2226
  return res.data;
1865
2227
  }
1866
2228
  const ANALYTICS_METRIC_KEYS = [
@@ -1923,724 +2285,390 @@ const ANALYTICS_METRICS = {
1923
2285
  requires: [
1924
2286
  "exerciseId",
1925
2287
  "dateStart",
1926
- "dateEnd"
1927
- ]
1928
- },
1929
- "working-max-history": {
1930
- path: "/v5/analytics/working-max-history/users",
1931
- scope: "user",
1932
- inputs: [
1933
- "exerciseId",
1934
- "dateStart",
1935
- "dateEnd",
1936
- "useMetric"
1937
- ],
1938
- requires: ["exerciseId"]
1939
- }
1940
- };
1941
- /**
1942
- * A serializable description of every analytics metric: its scope (does it need a `teamId` or
1943
- * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
1944
- * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
1945
- * shape by trial and error. These curated keys are deliberately NOT the raw category names from
1946
- * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
1947
- */
1948
- function analyticsMetricCatalog() {
1949
- return ANALYTICS_METRIC_KEYS.map((metric) => {
1950
- const spec = ANALYTICS_METRICS[metric];
1951
- return {
1952
- metric,
1953
- scope: spec.scope,
1954
- scopeParam: spec.scope === "team" ? "teamId" : "userIds",
1955
- requires: [...spec.requires],
1956
- optional: spec.inputs.filter((i) => !spec.requires.includes(i))
1957
- };
1958
- });
1959
- }
1960
- const ANALYTICS_BODY_KEY = {
1961
- date: "date",
1962
- dateStart: "date_start",
1963
- dateEnd: "date_end",
1964
- exerciseId: "exercise_id",
1965
- useMetric: "use_metric"
1966
- };
1967
- /**
1968
- * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
1969
- * athlete metrics need one or more `userIds` (passed together — the report returns a row per
1970
- * athlete). Throws a readable Error when a required input is missing or the call fails.
1971
- */
1972
- async function queryAnalytics(client, args) {
1973
- const spec = ANALYTICS_METRICS[args.metric];
1974
- const body = {};
1975
- if (spec.scope === "team") {
1976
- if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
1977
- body.teamId = args.teamId;
1978
- } else {
1979
- if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
1980
- body.user_ids = args.userIds.map((u) => String(u));
1981
- }
1982
- const inputs = {
1983
- date: args.date,
1984
- dateStart: args.dateStart,
1985
- dateEnd: args.dateEnd,
1986
- exerciseId: args.exerciseId,
1987
- useMetric: args.useMetric
1988
- };
1989
- const missing = spec.requires.filter((k) => inputs[k] === void 0);
1990
- if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
1991
- for (const k of spec.inputs) {
1992
- const v = inputs[k];
1993
- if (v === void 0) continue;
1994
- body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
1995
- }
1996
- const res = await client.request("POST", spec.path, { body });
1997
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1998
- return res.data;
1999
- }
2000
- /**
2001
- * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2002
- * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2003
- * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2004
- * given id, matched as a string. Throws when the roster fetch fails.
2005
- */
2006
- async function fetchTeamAthleteIds(client, teamId) {
2007
- const res = await client.request("GET", "/v5/athletes");
2008
- if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2009
- const rows = Array.isArray(res.data) ? res.data : [];
2010
- const want = String(teamId);
2011
- const ids = [];
2012
- for (const row of rows) {
2013
- if (row === null || typeof row !== "object") continue;
2014
- const rec = row;
2015
- if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2016
- const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2017
- if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2018
- }
2019
- return ids;
2020
- }
2021
- function toNum(v) {
2022
- const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2023
- return Number.isFinite(n) ? n : 0;
2024
- }
2025
- /**
2026
- * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2027
- * analytics report already returns the team in one call — one row per logged session across all
2028
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2029
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2030
- * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2031
- * all-time `fetchRosterActivity` snapshot, which has no date range.
2032
- */
2033
- async function teamVolume(client, args) {
2034
- if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2035
- const report = await queryAnalytics(client, {
2036
- metric: "training-summary-athlete",
2037
- userIds: args.athleteIds,
2038
- dateStart: args.dateStart,
2039
- dateEnd: args.dateEnd
2040
- });
2041
- const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2042
- const byAthlete = /* @__PURE__ */ new Map();
2043
- for (const row of rows) {
2044
- const athleteId = toNum(row.user_id);
2045
- if (athleteId === 0) continue;
2046
- const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2047
- const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2048
- const existing = byAthlete.get(athleteId);
2049
- if (existing) {
2050
- existing.sessions += 1;
2051
- existing.reps += toNum(row.reps);
2052
- existing.volume += toNum(row.volume);
2053
- if (date !== null) {
2054
- if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2055
- if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2056
- }
2057
- } else byAthlete.set(athleteId, {
2058
- athleteId,
2059
- name,
2060
- sessions: 1,
2061
- reps: toNum(row.reps),
2062
- volume: toNum(row.volume),
2063
- firstLoggedDate: date,
2064
- lastLoggedDate: date
2065
- });
2066
- }
2067
- const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2068
- const totals = athletes.reduce((acc, a) => ({
2069
- athletes: acc.athletes + 1,
2070
- sessions: acc.sessions + a.sessions,
2071
- reps: acc.reps + a.reps,
2072
- volume: acc.volume + a.volume
2073
- }), {
2074
- athletes: 0,
2075
- sessions: 0,
2076
- reps: 0,
2077
- volume: 0
2078
- });
2079
- return {
2080
- window: {
2081
- start: args.dateStart,
2082
- end: args.dateEnd
2083
- },
2084
- athletes,
2085
- totals
2086
- };
2087
- }
2088
- //#endregion
2089
- //#region src/main-lifts.ts
2090
- /**
2091
- * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2092
- * first family that matches, so the more specific / easily-confused families come before the broad
2093
- * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2094
- * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2095
- * This is the single place to edit the lift set.
2096
- */
2097
- const MAIN_LIFT_FAMILIES = [
2098
- {
2099
- key: "cleanjerk",
2100
- label: "Clean & Jerk",
2101
- matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2102
- },
2103
- {
2104
- key: "snatch",
2105
- label: "Snatch",
2106
- matches: (t) => t.includes("snatch")
2107
- },
2108
- {
2109
- key: "deadlift",
2110
- label: "Deadlift",
2111
- matches: (t) => t.includes("deadlift")
2112
- },
2113
- {
2114
- key: "squat",
2115
- label: "Squat",
2116
- matches: (t) => t.includes("squat")
2117
- },
2118
- {
2119
- key: "bench",
2120
- label: "Bench Press",
2121
- matches: (t) => t.includes("bench")
2122
- },
2123
- {
2124
- key: "overhead",
2125
- label: "Overhead Press",
2126
- matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2127
- }
2128
- ];
2129
- /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2130
- function classifyMainLift(title) {
2131
- const t = title.toLowerCase();
2132
- for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2133
- return null;
2134
- }
2135
- const DEFAULT_MONTHS = 12;
2136
- function pad2(n) {
2137
- return String(n).padStart(2, "0");
2138
- }
2139
- /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2140
- function isoDay(d) {
2141
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2142
- }
2143
- /**
2144
- * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2145
- * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2146
- * record of performed sets — buckets every performed exercise into a lift family, and for each
2147
- * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2148
- * families they never trained are simply absent. (The monthly calendar summary is not used: it
2149
- * comes back empty for some accounts that have logged sets in the range endpoint.)
2150
- */
2151
- async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2152
- const months = opts.months ?? DEFAULT_MONTHS;
2153
- const now = opts.now ?? /* @__PURE__ */ new Date();
2154
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2155
- const tally = /* @__PURE__ */ new Map();
2156
- let workouts = [];
2157
- try {
2158
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2159
- } catch {
2160
- workouts = [];
2161
- }
2162
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2163
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2164
- const family = classifyMainLift(ex.title);
2165
- if (family === null) continue;
2166
- const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2167
- const prev = byId.get(ex.exerciseId);
2168
- byId.set(ex.exerciseId, {
2169
- count: (prev?.count ?? 0) + 1,
2170
- title: prev?.title ?? ex.title
2171
- });
2172
- tally.set(family, byId);
2173
- }
2174
- const lifts = [];
2175
- for (const family of MAIN_LIFT_FAMILIES) {
2176
- const byId = tally.get(family.key);
2177
- if (!byId || byId.size === 0) continue;
2178
- let best = null;
2179
- for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2180
- exerciseId,
2181
- count,
2182
- title
2183
- };
2184
- if (best) lifts.push({
2185
- family: family.key,
2186
- label: family.label,
2187
- exerciseId: best.exerciseId,
2188
- title: best.title
2189
- });
2190
- }
2191
- return {
2192
- athleteId,
2193
- athleteName: null,
2194
- lifts
2195
- };
2196
- }
2197
- const PR_CONCURRENCY = 5;
2198
- /** The heaviest PR on an exercise's board (ties broken by more reps). */
2199
- function bestPr(liftPRs) {
2200
- let best = null;
2201
- for (const pr of liftPRs) {
2202
- const weight = coerceNum(pr.weight);
2203
- if (weight === null) continue;
2204
- const reps = coerceInt(pr.reps);
2205
- if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2206
- weight,
2207
- reps,
2208
- units: pr.units,
2209
- date: pr.date
2210
- };
2211
- }
2212
- return best;
2213
- }
2214
- /**
2215
- * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2216
- * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2217
- * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2218
- * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2219
- * render a stable row of columns.
2220
- */
2221
- async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2222
- const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2223
- const byFamily = new Map(lifts.map((l) => [l.family, l]));
2224
- return {
2225
- athleteId,
2226
- athleteName,
2227
- prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2228
- const lift = byFamily.get(family.key);
2229
- const base = {
2230
- family: family.key,
2231
- label: family.label
2232
- };
2233
- const empty = {
2234
- exerciseId: null,
2235
- title: null,
2236
- weight: null,
2237
- reps: null,
2238
- units: null,
2239
- date: null
2240
- };
2241
- if (!lift) return {
2242
- ...base,
2243
- ...empty
2244
- };
2245
- const known = {
2246
- exerciseId: lift.exerciseId,
2247
- title: lift.title
2248
- };
2249
- try {
2250
- const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2251
- return {
2252
- ...base,
2253
- ...known,
2254
- weight: best?.weight ?? null,
2255
- reps: best?.reps ?? null,
2256
- units: best?.units ?? null,
2257
- date: best?.date ?? null
2258
- };
2259
- } catch {
2260
- return {
2261
- ...base,
2262
- ...known,
2263
- weight: null,
2264
- reps: null,
2265
- units: null,
2266
- date: null
2267
- };
2268
- }
2269
- })
2270
- };
2271
- }
2272
- const ROSTER_CONCURRENCY = 4;
2273
- /**
2274
- * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2275
- * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2276
- * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2277
- * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2278
- * primitive the CLI, the MCP tool, and the warehouse store all build on.
2279
- */
2280
- async function fetchRosterMainLiftPRs(client, opts = {}) {
2281
- const roster = await fetchCoachRoster(client, opts.athleteIds);
2282
- const inner = {
2283
- ...opts.months !== void 0 ? { months: opts.months } : {},
2284
- ...opts.now !== void 0 ? { now: opts.now } : {}
2285
- };
2286
- return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2287
- const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2288
- return {
2289
- athleteId: athlete.id,
2290
- athleteName: result.athleteName ?? athlete.name,
2291
- prs: result.prs
2292
- };
2293
- });
2294
- }
2295
- //#endregion
2296
- //#region src/util.ts
2297
- /**
2298
- * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2299
- * spread into an object under `exactOptionalPropertyTypes` without the per-key
2300
- * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2301
- * optional ones lose `undefined` from their value type.
2302
- *
2303
- * Example:
2304
- * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2305
- */
2306
- function definedProps(obj) {
2307
- const result = {};
2308
- for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2309
- return result;
2310
- }
2311
- //#endregion
2312
- //#region src/workout-encode.ts
2313
- const LEADERBOARD_TYPE = {
2314
- completion: 0,
2315
- "for completion": 0,
2316
- weight: 1,
2317
- lb: 1,
2318
- load: 1,
2319
- reps: 2,
2320
- rep: 2,
2321
- rounds: 3,
2322
- round: 3,
2323
- time: 4,
2324
- yards: 5,
2325
- yd: 5,
2326
- meters: 6,
2327
- m: 6,
2328
- feet: 7,
2329
- ft: 7,
2330
- calories: 8,
2331
- cal: 8,
2332
- cals: 8,
2333
- miles: 10,
2334
- mi: 10,
2335
- inches: 12,
2336
- in: 12,
2337
- watts: 15,
2338
- w: 15,
2339
- velocity: 17,
2340
- "m/s": 17,
2341
- seconds: 18,
2342
- sec: 18,
2343
- s: 18
2344
- };
2345
- const LEADERBOARD_LABEL = {
2346
- 0: "For Completion",
2347
- 1: "Weight",
2348
- 2: "Reps",
2349
- 3: "Rounds",
2350
- 4: "Time",
2351
- 5: "Yards",
2352
- 6: "Meters",
2353
- 7: "Feet",
2354
- 8: "Calories",
2355
- 10: "Miles",
2356
- 12: "Inches",
2357
- 13: "Other",
2358
- 15: "Watts",
2359
- 16: "Percent",
2360
- 17: "Velocity",
2361
- 18: "Seconds"
2362
- };
2363
- function resolveLeaderboard(block) {
2364
- const lb = block.leaderboard;
2365
- if (lb === void 0 || lb === null) return {
2366
- isRedzone: null,
2367
- redzoneType: 0,
2368
- smallerIsBetter: null,
2369
- redzoneInstruction: ""
2370
- };
2371
- let unit;
2372
- let instruction = "";
2373
- let lowest;
2374
- if (typeof lb === "object") {
2375
- unit = lb.unit ?? lb.type;
2376
- instruction = lb.instruction ?? "";
2377
- lowest = lb.lowest_wins;
2378
- } else unit = lb;
2379
- let rz;
2380
- if (typeof unit === "string") {
2381
- const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2382
- if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2383
- rz = found;
2384
- } else if (typeof unit === "number") rz = Math.trunc(unit);
2385
- else throw new Error("Leaderboard requires a unit.");
2386
- if (lowest === void 0) lowest = rz === 4 || rz === 18;
2387
- return {
2388
- isRedzone: 1,
2389
- redzoneType: rz,
2390
- smallerIsBetter: lowest ? 1 : 0,
2391
- redzoneInstruction: instruction
2392
- };
2393
- }
2394
- function slots(values, n = 10) {
2395
- const out = [];
2396
- for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2397
- return out;
2398
- }
2399
- function repsList(ex) {
2400
- const reps = ex.reps;
2401
- if (Array.isArray(reps)) return reps.map((r) => String(r));
2402
- if (reps === void 0 || reps === null) return [];
2403
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2404
- return Array.from({ length: sets }, () => String(reps));
2405
- }
2406
- /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2407
- function makeExercise(ex, workoutSetId, order, key) {
2408
- const reps = repsList(ex);
2409
- let instruction = ex.instr ?? "";
2410
- if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2411
- const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2412
- const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2413
- let count = reps.length;
2414
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2415
- let param2Type;
2416
- let param2Values;
2417
- if (hasWeight) {
2418
- param2Type = ex.param_2_type ?? 1;
2419
- param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2420
- } else {
2421
- param2Type = 0;
2422
- param2Values = null;
2423
- }
2424
- const entry = {
2425
- exercise_id: ex.id,
2426
- workout_set_id: workoutSetId,
2427
- set_id: workoutSetId,
2428
- setKey: workoutSetId,
2429
- title: ex.title ?? "",
2430
- instruction,
2431
- order,
2432
- param_1_type: ex.param_1_type ?? 3,
2433
- param_2_type: param2Type,
2434
- workout_set_exercise_template_id: null,
2435
- no_sets: 0,
2436
- param_count: count,
2437
- set_num: count,
2438
- key,
2439
- video_url: "",
2440
- thumbnail_url: "",
2441
- tags: [],
2442
- eType: "e",
2443
- use_count: 0
2444
- };
2445
- const p1 = slots(reps);
2446
- const p2 = slots(param2Values);
2447
- for (let i = 0; i < 10; i += 1) {
2448
- entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2449
- entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2288
+ "dateEnd"
2289
+ ]
2290
+ },
2291
+ "working-max-history": {
2292
+ path: "/v5/analytics/working-max-history/users",
2293
+ scope: "user",
2294
+ inputs: [
2295
+ "exerciseId",
2296
+ "dateStart",
2297
+ "dateEnd",
2298
+ "useMetric"
2299
+ ],
2300
+ requires: ["exerciseId"]
2450
2301
  }
2451
- return entry;
2452
- }
2453
- function buildBlockPayload(blocks, workoutId) {
2454
- return blocks.map((b, i) => {
2455
- const lb = resolveLeaderboard(b);
2302
+ };
2303
+ /**
2304
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
2305
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
2306
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
2307
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
2308
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
2309
+ */
2310
+ function analyticsMetricCatalog() {
2311
+ return ANALYTICS_METRIC_KEYS.map((metric) => {
2312
+ const spec = ANALYTICS_METRICS[metric];
2456
2313
  return {
2457
- workout_id: workoutId,
2458
- order: i + 1,
2459
- type: b.type ?? 2,
2460
- instruction: b.instruction ?? "",
2461
- is_redzone: lb.isRedzone,
2462
- redzone_type: lb.redzoneType,
2463
- smaller_is_better: lb.smallerIsBetter,
2464
- redzone_instruction: lb.redzoneInstruction,
2465
- exercises: [],
2466
- exerciseKeys: [],
2467
- key: `k::${workoutId}${i + 1}`,
2468
- title: b.title
2314
+ metric,
2315
+ scope: spec.scope,
2316
+ scopeParam: spec.scope === "team" ? "teamId" : "userIds",
2317
+ requires: [...spec.requires],
2318
+ optional: spec.inputs.filter((i) => !spec.requires.includes(i))
2469
2319
  };
2470
2320
  });
2471
2321
  }
2472
- function unitOr(t) {
2473
- return unitLabel(t) ?? "?";
2474
- }
2475
- /** Flag spec params the API will silently override to the exercise's fixed units. */
2476
- function unitAdvisory(blockTitle, ex, defaults) {
2477
- const notes = [];
2478
- const warnings = [];
2479
- const u = unitOr;
2480
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2481
- if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
2482
- const sentP1 = ex.param_1_type;
2483
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2484
- const sp1 = Math.trunc(Number(sentP1));
2485
- warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
2486
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2487
- if (ex.weight !== void 0 && ex.weight !== null) {
2488
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2489
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2490
- if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2491
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2322
+ const ANALYTICS_BODY_KEY = {
2323
+ date: "date",
2324
+ dateStart: "date_start",
2325
+ dateEnd: "date_end",
2326
+ exerciseId: "exercise_id",
2327
+ useMetric: "use_metric"
2328
+ };
2329
+ /**
2330
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2331
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2332
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
2333
+ */
2334
+ async function queryAnalytics(client, args) {
2335
+ const spec = ANALYTICS_METRICS[args.metric];
2336
+ const body = {};
2337
+ if (spec.scope === "team") {
2338
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
2339
+ body.teamId = args.teamId;
2340
+ } else {
2341
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
2342
+ body.user_ids = args.userIds.map((u) => String(u));
2492
2343
  }
2493
- return {
2494
- notes,
2495
- warnings
2344
+ const inputs = {
2345
+ date: args.date,
2346
+ dateStart: args.dateStart,
2347
+ dateEnd: args.dateEnd,
2348
+ exerciseId: args.exerciseId,
2349
+ useMetric: args.useMetric
2496
2350
  };
2351
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
2352
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
2353
+ for (const k of spec.inputs) {
2354
+ const v = inputs[k];
2355
+ if (v === void 0) continue;
2356
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
2357
+ }
2358
+ const res = await client.request("POST", spec.path, { body });
2359
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2360
+ return res.data;
2497
2361
  }
2498
2362
  /**
2499
- * Run unit advisories across a whole block list against an exercise index. Shared by the
2500
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2501
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2502
- * advisory is silently dropped.
2363
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2364
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2365
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2366
+ * given id, matched as a string. Throws when the roster fetch fails.
2503
2367
  */
2504
- async function collectAdvisories(blocks, index) {
2505
- await index.ensureFresh();
2506
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2507
- block: b,
2508
- ex
2509
- })));
2510
- const defaults = await Promise.all(pairs.map((p) => {
2511
- const id = Number(p.ex.id);
2512
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2513
- }));
2514
- const notes = [];
2515
- const warnings = [];
2516
- pairs.forEach((p, i) => {
2517
- const def = defaults[i];
2518
- if (!def) return;
2519
- const advisory = unitAdvisory(p.block.title, p.ex, def);
2520
- notes.push(...advisory.notes);
2521
- warnings.push(...advisory.warnings);
2368
+ async function fetchTeamAthleteIds(client, teamId) {
2369
+ const res = await client.request("GET", "/v5/athletes");
2370
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2371
+ const rows = Array.isArray(res.data) ? res.data : [];
2372
+ const want = String(teamId);
2373
+ const ids = [];
2374
+ for (const row of rows) {
2375
+ if (row === null || typeof row !== "object") continue;
2376
+ const rec = row;
2377
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2378
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2379
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2380
+ }
2381
+ return ids;
2382
+ }
2383
+ function toNum(v) {
2384
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2385
+ return Number.isFinite(n) ? n : 0;
2386
+ }
2387
+ /**
2388
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2389
+ * analytics report already returns the team in one call — one row per logged session across all
2390
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2391
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2392
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2393
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
2394
+ */
2395
+ async function teamVolume(client, args) {
2396
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2397
+ const report = await queryAnalytics(client, {
2398
+ metric: "training-summary-athlete",
2399
+ userIds: args.athleteIds,
2400
+ dateStart: args.dateStart,
2401
+ dateEnd: args.dateEnd
2402
+ });
2403
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2404
+ const byAthlete = /* @__PURE__ */ new Map();
2405
+ for (const row of rows) {
2406
+ const athleteId = toNum(row.user_id);
2407
+ if (athleteId === 0) continue;
2408
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2409
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2410
+ const existing = byAthlete.get(athleteId);
2411
+ if (existing) {
2412
+ existing.sessions += 1;
2413
+ existing.reps += toNum(row.reps);
2414
+ existing.volume += toNum(row.volume);
2415
+ if (date !== null) {
2416
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2417
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2418
+ }
2419
+ } else byAthlete.set(athleteId, {
2420
+ athleteId,
2421
+ name,
2422
+ sessions: 1,
2423
+ reps: toNum(row.reps),
2424
+ volume: toNum(row.volume),
2425
+ firstLoggedDate: date,
2426
+ lastLoggedDate: date
2427
+ });
2428
+ }
2429
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2430
+ const totals = athletes.reduce((acc, a) => ({
2431
+ athletes: acc.athletes + 1,
2432
+ sessions: acc.sessions + a.sessions,
2433
+ reps: acc.reps + a.reps,
2434
+ volume: acc.volume + a.volume
2435
+ }), {
2436
+ athletes: 0,
2437
+ sessions: 0,
2438
+ reps: 0,
2439
+ volume: 0
2522
2440
  });
2523
2441
  return {
2524
- notes,
2525
- warnings
2442
+ window: {
2443
+ start: args.dateStart,
2444
+ end: args.dateEnd
2445
+ },
2446
+ athletes,
2447
+ totals
2526
2448
  };
2527
2449
  }
2528
2450
  //#endregion
2529
- //#region src/workout-session.ts
2530
- async function req(client, method, path, body) {
2531
- const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2532
- if (!res.ok) {
2533
- const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2534
- throw new Error(`${method} ${path} failed (HTTP ${res.status}): ${detail}`);
2451
+ //#region src/main-lifts.ts
2452
+ /**
2453
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2454
+ * first family that matches, so the more specific / easily-confused families come before the broad
2455
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2456
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2457
+ * This is the single place to edit the lift set.
2458
+ */
2459
+ const MAIN_LIFT_FAMILIES = [
2460
+ {
2461
+ key: "cleanjerk",
2462
+ label: "Clean & Jerk",
2463
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2464
+ },
2465
+ {
2466
+ key: "snatch",
2467
+ label: "Snatch",
2468
+ matches: (t) => t.includes("snatch")
2469
+ },
2470
+ {
2471
+ key: "deadlift",
2472
+ label: "Deadlift",
2473
+ matches: (t) => t.includes("deadlift")
2474
+ },
2475
+ {
2476
+ key: "squat",
2477
+ label: "Squat",
2478
+ matches: (t) => t.includes("squat")
2479
+ },
2480
+ {
2481
+ key: "bench",
2482
+ label: "Bench Press",
2483
+ matches: (t) => t.includes("bench")
2484
+ },
2485
+ {
2486
+ key: "overhead",
2487
+ label: "Overhead Press",
2488
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2535
2489
  }
2536
- return res.data;
2490
+ ];
2491
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2492
+ function classifyMainLift(title) {
2493
+ const t = title.toLowerCase();
2494
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2495
+ return null;
2537
2496
  }
2538
- function createPath(opts) {
2539
- if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2540
- if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2541
- const [y, m, d] = opts.date;
2542
- return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2497
+ const DEFAULT_MONTHS = 12;
2498
+ function pad2(n) {
2499
+ return String(n).padStart(2, "0");
2543
2500
  }
2544
- async function buildSession(client, opts) {
2545
- const sess = await req(client, "POST", createPath(opts), {});
2546
- checkResponse(sessionCreateResponseSchema, sess, "session create");
2547
- const workoutId = Number(sess.workout_id);
2548
- const pwId = Number(sess.id);
2549
- const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(opts.blocks, workoutId));
2550
- const byOrder = new Map(created.map((b) => [b.order, b.id]));
2551
- let counter = 0;
2552
- const payloads = opts.blocks.map((block, i) => {
2553
- const wsid = byOrder.get(i + 1);
2554
- if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2555
- return block.exercises.map((ex, j) => {
2556
- counter += 1;
2557
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2501
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2502
+ function isoDay(d) {
2503
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2504
+ }
2505
+ /**
2506
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2507
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2508
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
2509
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2510
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
2511
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
2512
+ */
2513
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2514
+ const months = opts.months ?? DEFAULT_MONTHS;
2515
+ const now = opts.now ?? /* @__PURE__ */ new Date();
2516
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2517
+ const tally = /* @__PURE__ */ new Map();
2518
+ let workouts = [];
2519
+ try {
2520
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2521
+ } catch {
2522
+ workouts = [];
2523
+ }
2524
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2525
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2526
+ const family = classifyMainLift(ex.title);
2527
+ if (family === null) continue;
2528
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2529
+ const prev = byId.get(ex.exerciseId);
2530
+ byId.set(ex.exerciseId, {
2531
+ count: (prev?.count ?? 0) + 1,
2532
+ title: prev?.title ?? ex.title
2533
+ });
2534
+ tally.set(family, byId);
2535
+ }
2536
+ const lifts = [];
2537
+ for (const family of MAIN_LIFT_FAMILIES) {
2538
+ const byId = tally.get(family.key);
2539
+ if (!byId || byId.size === 0) continue;
2540
+ let best = null;
2541
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2542
+ exerciseId,
2543
+ count,
2544
+ title
2545
+ };
2546
+ if (best) lifts.push({
2547
+ family: family.key,
2548
+ label: family.label,
2549
+ exerciseId: best.exerciseId,
2550
+ title: best.title
2558
2551
  });
2559
- });
2560
- await Promise.all(payloads.map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2561
- if (opts.instruction !== void 0 && opts.instruction !== "") {
2562
- const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2563
- await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2564
2552
  }
2565
- if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2566
2553
  return {
2567
- pwId,
2568
- workoutId
2554
+ athleteId,
2555
+ athleteName: null,
2556
+ lifts
2569
2557
  };
2570
2558
  }
2559
+ const PR_CONCURRENCY = 5;
2560
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
2561
+ function bestPr(liftPRs) {
2562
+ let best = null;
2563
+ for (const pr of liftPRs) {
2564
+ const weight = coerceNum(pr.weight);
2565
+ if (weight === null) continue;
2566
+ const reps = coerceInt(pr.reps);
2567
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2568
+ weight,
2569
+ reps,
2570
+ units: pr.units,
2571
+ date: pr.date
2572
+ };
2573
+ }
2574
+ return best;
2575
+ }
2571
2576
  /**
2572
- * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2573
- * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2574
- * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2575
- * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2577
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2578
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2579
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2580
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2581
+ * render a stable row of columns.
2576
2582
  */
2577
- async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2578
- const body = {
2579
- ...pw,
2580
- instruction,
2581
- sets: blockIds,
2582
- setKeys: blockIds
2583
- };
2584
- await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2585
- }
2586
- async function removeSession(client, programId, pwId) {
2587
- await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2588
- programId,
2589
- pwId
2590
- });
2591
- }
2592
- async function publishSession(client, pwId) {
2593
- await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2594
- }
2595
- function str$1(value) {
2596
- return value === void 0 || value === null ? "" : String(value);
2597
- }
2598
- async function readSession(client, programId, date, pwId) {
2599
- const [y, m, d] = date;
2600
- const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2601
- checkResponse(programsEditResponseSchema, data, "programs edit");
2602
- const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2603
- if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2604
- const setsObj = pw.sets ?? {};
2605
- const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2583
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2584
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2585
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
2606
2586
  return {
2607
- pwId,
2608
- date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
2609
- published: pw.published,
2610
- instruction: str$1(pw.instruction),
2611
- blocks
2587
+ athleteId,
2588
+ athleteName,
2589
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2590
+ const lift = byFamily.get(family.key);
2591
+ const base = {
2592
+ family: family.key,
2593
+ label: family.label
2594
+ };
2595
+ const empty = {
2596
+ exerciseId: null,
2597
+ title: null,
2598
+ weight: null,
2599
+ reps: null,
2600
+ units: null,
2601
+ date: null
2602
+ };
2603
+ if (!lift) return {
2604
+ ...base,
2605
+ ...empty
2606
+ };
2607
+ const known = {
2608
+ exerciseId: lift.exerciseId,
2609
+ title: lift.title
2610
+ };
2611
+ try {
2612
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2613
+ return {
2614
+ ...base,
2615
+ ...known,
2616
+ weight: best?.weight ?? null,
2617
+ reps: best?.reps ?? null,
2618
+ units: best?.units ?? null,
2619
+ date: best?.date ?? null
2620
+ };
2621
+ } catch {
2622
+ return {
2623
+ ...base,
2624
+ ...known,
2625
+ weight: null,
2626
+ reps: null,
2627
+ units: null,
2628
+ date: null
2629
+ };
2630
+ }
2631
+ })
2612
2632
  };
2613
2633
  }
2614
- function readBlock(b) {
2615
- const rz = coerceInt(b.redzone_type);
2616
- let leaderboard = null;
2617
- if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2618
- const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2619
- return {
2620
- order: Number(b.order),
2621
- title: str$1(b.title),
2622
- leaderboard,
2623
- exercises
2634
+ const ROSTER_CONCURRENCY = 4;
2635
+ /**
2636
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2637
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2638
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2639
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2640
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
2641
+ */
2642
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
2643
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
2644
+ const inner = {
2645
+ ...opts.months !== void 0 ? { months: opts.months } : {},
2646
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2624
2647
  };
2648
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2649
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2650
+ return {
2651
+ athleteId: athlete.id,
2652
+ athleteName: result.athleteName ?? athlete.name,
2653
+ prs: result.prs
2654
+ };
2655
+ });
2625
2656
  }
2626
- function readExercise(ex) {
2627
- const reps = [];
2628
- const load = [];
2629
- for (let i = 1; i <= 10; i += 1) {
2630
- const r = str$1(ex[`param_1_data_${i}`]);
2631
- if (r !== "") reps.push(r);
2632
- const w = str$1(ex[`param_2_data_${i}`]);
2633
- if (w !== "") load.push(w);
2634
- }
2635
- return {
2636
- order: Number(ex.order),
2637
- title: str$1(ex.title),
2638
- reps,
2639
- primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2640
- load,
2641
- loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2642
- instruction: str$1(ex.instruction)
2643
- };
2657
+ //#endregion
2658
+ //#region src/util.ts
2659
+ /**
2660
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2661
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
2662
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2663
+ * optional ones lose `undefined` from their value type.
2664
+ *
2665
+ * Example:
2666
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2667
+ */
2668
+ function definedProps(obj) {
2669
+ const result = {};
2670
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2671
+ return result;
2644
2672
  }
2645
2673
  //#endregion
2646
2674
  //#region src/messaging.ts
@@ -2875,4 +2903,4 @@ var ExerciseLibrary = class {
2875
2903
  }
2876
2904
  };
2877
2905
  //#endregion
2878
- export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
2906
+ export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };