@trainheroic-unofficial/cli 1.5.0 → 1.6.0

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @trainheroic-unofficial/cli
2
2
 
3
- A command-line tool for the TrainHeroic coaching API. Takes credentials from the environment, prints JSON.
3
+ A command-line tool for the TrainHeroic API. Takes credentials from the environment, prints JSON.
4
4
 
5
5
  Part of the [trainheroic-unofficial](../../README.md) workspace.
6
6
 
package/dist/cli.mjs CHANGED
@@ -241,6 +241,16 @@ const logSessionArgsSchema = z.object({
241
241
  * `athleteId` whose session is being logged on their behalf.
242
242
  */
243
243
  const coachLogSessionArgsSchema = logSessionArgsSchema.extend({ athleteId: idArgSchema });
244
+ /**
245
+ * Args for removing a personal (athlete-created) workout session. `programWorkoutId` is the
246
+ * range item's top-level `id`; `date` is that session's day, used to look the item back up so the
247
+ * write can confirm it is a personal session (`personal_cal === true`) before deleting. A
248
+ * coach-scheduled workout is never removed this way.
249
+ */
250
+ const athleteSessionRemoveArgsSchema = z.object({
251
+ programWorkoutId: idArgSchema,
252
+ date: dateString
253
+ });
244
254
  //#endregion
245
255
  //#region ../dto/src/exercise.ts
246
256
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
@@ -610,6 +620,22 @@ function str$1(v) {
610
620
  return typeof v === "string" && v !== "" ? v : null;
611
621
  }
612
622
  /**
623
+ * The display title of a saved-copy exercise row, preferring `exercise_title`, then `title`, then
624
+ * the given fallback. The saved-workout shape carries the title under either key depending on the
625
+ * endpoint, so this is the one place that reconciles them.
626
+ */
627
+ function exerciseTitle(ex, fallback = "") {
628
+ return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
629
+ }
630
+ /**
631
+ * True when a program-workout range item is a personal (athlete-created) session rather than a
632
+ * coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
633
+ * definition every consumer (presenter, find-or-create, the remove guard) reads through.
634
+ */
635
+ function isPersonalSession(pw) {
636
+ return isRecord(pw) && pw.personal_cal === true;
637
+ }
638
+ /**
613
639
  * Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
614
640
  * exact title, then prefix, then count of matched tokens, with shorter titles and
615
641
  * standard (non-custom) exercises preferred on ties.
@@ -943,6 +969,7 @@ function presentAthleteWorkout(raw) {
943
969
  team: str$1(rec.team_title),
944
970
  instruction: str$1(workout.instruction),
945
971
  logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
972
+ personal: isPersonalSession(rec),
946
973
  blocks
947
974
  };
948
975
  }
@@ -1003,7 +1030,7 @@ function presentLogTargets(list) {
1003
1030
  if (id === null) return null;
1004
1031
  return {
1005
1032
  savedWorkoutSetExerciseId: id,
1006
- title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
1033
+ title: exerciseTitle(ex),
1007
1034
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1008
1035
  prescribed: prescribedSets(ex),
1009
1036
  performed: performedSets(ex)
@@ -1052,6 +1079,7 @@ function summarizeAthleteWorkouts(list) {
1052
1079
  program: w.program,
1053
1080
  team: w.team,
1054
1081
  logged: w.logged,
1082
+ personal: w.personal,
1055
1083
  exerciseCount,
1056
1084
  performedCount
1057
1085
  };
@@ -1278,8 +1306,7 @@ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
1278
1306
  if (setId !== null) {
1279
1307
  const exLabels = exercises.map((ex) => {
1280
1308
  const exId = coerceInt(ex.id);
1281
- const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1282
- return exId === null ? null : `${exId} (${title})`;
1309
+ return exId === null ? null : `${exId} (${exerciseTitle(ex, "exercise")})`;
1283
1310
  }).filter((x) => x !== null);
1284
1311
  available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
1285
1312
  }
@@ -1456,8 +1483,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1456
1483
  if (!ex) {
1457
1484
  const valid = exercises.map((e) => {
1458
1485
  const id = coerceInt(e.id);
1459
- const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
1460
- return id === null ? null : `${id} (${title})`;
1486
+ return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
1461
1487
  }).filter((x) => x !== null);
1462
1488
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1463
1489
  }
@@ -1532,17 +1558,30 @@ async function addExercisesToWorkout(client, workoutId, exercises) {
1532
1558
  return res.data;
1533
1559
  }
1534
1560
  /**
1561
+ * DELETE /v5/programWorkouts/{programWorkoutId} — remove a personal (athlete-created) workout
1562
+ * session from the athlete's own calendar. Re-reads the day and removes ONLY a personal session
1563
+ * (`personal_cal`): it throws if no workout with that id is on the date, or if the target is a
1564
+ * coach-scheduled workout (which is not the athlete's to delete). This guard lives here, at the
1565
+ * delete itself, so no caller can issue the DELETE against a coach workout by skipping a check.
1566
+ * Throws on a non-ok response.
1567
+ */
1568
+ async function removePersonalWorkout(client, args) {
1569
+ const target = (await fetchAthleteWorkouts(client, args.date, args.date)).find((pw) => coerceInt(pw.id) === args.programWorkoutId);
1570
+ if (target === void 0) throw new Error(`No workout with id ${args.programWorkoutId} on ${args.date}. Get the id and date from athlete_workouts.`);
1571
+ if (!isPersonalSession(target)) throw new Error(`Workout ${args.programWorkoutId} on ${args.date} is a coach-scheduled workout, not a personal session, so it can't be removed. To change logged results on a scheduled workout, use athlete_log_set.`);
1572
+ const res = await client.request("DELETE", `/v5/programWorkouts/${args.programWorkoutId}`);
1573
+ if (!res.ok) throw new Error(`Remove personal workout failed (HTTP ${res.status}).`);
1574
+ }
1575
+ /**
1535
1576
  * Find a personal-calendar session already on the given day. The range marks these with
1536
1577
  * `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
1537
1578
  * first one's workoutId, or null when the day has no personal session.
1538
1579
  */
1539
1580
  function findPersonalSessionWorkoutId(workouts) {
1540
1581
  for (const pw of workouts) {
1541
- const rec = pw;
1542
- if (rec.personal_cal === true) {
1543
- const workoutId = coerceInt(rec.workout_id);
1544
- if (workoutId !== null) return workoutId;
1545
- }
1582
+ if (!isPersonalSession(pw)) continue;
1583
+ const workoutId = coerceInt(pw.workout_id);
1584
+ if (workoutId !== null) return workoutId;
1546
1585
  }
1547
1586
  return null;
1548
1587
  }
@@ -1573,7 +1612,11 @@ function indexAddedExercises(added) {
1573
1612
  }
1574
1613
  return out;
1575
1614
  }
1576
- /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
1615
+ /**
1616
+ * Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
1617
+ * carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
1618
+ * title) without re-walking. The one saved-copy traversal the by-exercise paths share.
1619
+ */
1577
1620
  function eachPrescribedExercise(workouts) {
1578
1621
  const rows = [];
1579
1622
  for (const pw of workouts) {
@@ -1588,6 +1631,7 @@ function eachPrescribedExercise(workouts) {
1588
1631
  if (savedWorkoutSetId === null) continue;
1589
1632
  const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1590
1633
  for (const ex of exercises) if (isRecord(ex)) rows.push({
1634
+ pw: rec,
1591
1635
  savedWorkoutSetId,
1592
1636
  ex
1593
1637
  });
@@ -1612,14 +1656,39 @@ function findPrescribedExercise(workouts, exerciseId, used) {
1612
1656
  }
1613
1657
  return null;
1614
1658
  }
1659
+ /**
1660
+ * Find prescribed exercises on coach-scheduled (non-personal) workouts that day matching any of the
1661
+ * given exercise ids. Used to warn after an ad-hoc log that the same lift was already on the
1662
+ * athlete's scheduled workout — a caller can then point at {@link logAthleteSet}. Personal sessions
1663
+ * (`personal_cal === true`) are skipped: the ad-hoc log itself lands there, so they are not an
1664
+ * alternative. One row per matching saved-set exercise, dropping any with an unresolvable id.
1665
+ */
1666
+ function findScheduledMatches(workouts, exerciseIds) {
1667
+ const out = [];
1668
+ for (const { pw, savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
1669
+ if (isPersonalSession(pw)) continue;
1670
+ const exerciseId = coerceInt(ex.exercise_id);
1671
+ const savedWorkoutSetExerciseId = coerceInt(ex.id);
1672
+ if (exerciseId === null || savedWorkoutSetExerciseId === null) continue;
1673
+ if (!exerciseIds.has(exerciseId)) continue;
1674
+ out.push({
1675
+ exerciseId,
1676
+ title: exerciseTitle(ex),
1677
+ program: str$1(pw.program_title),
1678
+ workoutTitle: str$1(pw.workout_title) ?? "",
1679
+ savedWorkoutSetId,
1680
+ savedWorkoutSetExerciseId
1681
+ });
1682
+ }
1683
+ return out;
1684
+ }
1615
1685
  /** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
1616
1686
  function prescribedExerciseLabels(workouts) {
1617
1687
  const labels = [];
1618
1688
  for (const { ex } of eachPrescribedExercise(workouts)) {
1619
1689
  const id = coerceInt(ex.exercise_id);
1620
1690
  if (id === null) continue;
1621
- const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1622
- labels.push(`${id} (${title})`);
1691
+ labels.push(`${id} (${exerciseTitle(ex, "exercise")})`);
1623
1692
  }
1624
1693
  return labels;
1625
1694
  }
@@ -1662,7 +1731,8 @@ async function logResolvedExercises(client, target, date, resolved) {
1662
1731
  */
1663
1732
  async function logAdHocSession(client, args) {
1664
1733
  if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1665
- const existing = findPersonalSessionWorkoutId(await fetchAthleteWorkouts(client, args.date, args.date));
1734
+ const day = await fetchAthleteWorkouts(client, args.date, args.date);
1735
+ const existing = findPersonalSessionWorkoutId(day);
1666
1736
  const created = existing === null;
1667
1737
  const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
1668
1738
  const withOrder = args.exercises.map((e, i) => ({
@@ -1686,11 +1756,14 @@ async function logAdHocSession(client, args) {
1686
1756
  };
1687
1757
  });
1688
1758
  const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
1689
- return {
1759
+ const result = {
1690
1760
  date: args.date,
1691
1761
  created,
1692
1762
  sets
1693
1763
  };
1764
+ const scheduledAlternatives = findScheduledMatches(day, new Set(args.exercises.map((e) => e.exerciseId)));
1765
+ if (scheduledAlternatives.length > 0) result.scheduledAlternatives = scheduledAlternatives;
1766
+ return result;
1694
1767
  }
1695
1768
  /**
1696
1769
  * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
@@ -2883,7 +2956,7 @@ async function saveSession(sessionId) {
2883
2956
  }
2884
2957
  //#endregion
2885
2958
  //#region src/cli.ts
2886
- const HELP = `trainheroic — command-line tool for the TrainHeroic coaching API
2959
+ const HELP = `trainheroic — command-line tool for the TrainHeroic API
2887
2960
 
2888
2961
  Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
2889
2962
  Coaching commands live under 'coach'; your own training lives under 'athlete'.
@@ -2985,15 +3058,17 @@ Coach — manage a roster (needs a coach account):
2985
3058
 
2986
3059
  Athlete — the logged-in user's own training (a coach account works too):
2987
3060
  athlete whoami | profile [--metric] | prefs | working-maxes
2988
- athlete workouts --start Y-M-D --end Y-M-D [--raw] [--log-ids] [--logged-only] [--limit N] [--summary] (--log-ids: the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs)
3061
+ athlete workouts --start Y-M-D --end Y-M-D [--raw] [--logged-only] [--limit N] [--summary] (reads what you did; for the log ids use 'athlete log-targets')
3062
+ athlete log-targets --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw] (the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs; --program narrows when several workouts share a date)
2989
3063
  athlete exercises [--q <text>] [--limit N]
2990
3064
  athlete history <exerciseId> [--raw]
2991
3065
  athlete prs <exerciseId>
2992
3066
  athlete stats <exerciseId> --date Y-M-D
2993
3067
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2994
3068
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2995
- athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete workouts ... --log-ids'; each set fills the next position, add "slot":K to target the K-th; a partial log records only what you send)
3069
+ athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete log-targets'; each set fills the next position, add "slot":K to target the K-th; a partial log records only what you send)
2996
3070
  athlete log-session --date Y-M-D <exercisesJson>|--file f --yes (log OFF-PLAN work with no prescription — creates/reuses a personal session for the date, then logs it; exerciseIds from 'athlete exercises')
3071
+ athlete session-remove --id <programWorkoutId> --date Y-M-D --yes (delete a stray PERSONAL session; the id is the session 'id' from 'athlete workouts')
2997
3072
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2998
3073
  `;
2999
3074
  function out(value) {
@@ -3357,10 +3432,57 @@ async function cmdAthleteLogSession(client, a) {
3357
3432
  exercises: await jsonInput(positionals[0], values.file)
3358
3433
  }, "log-session args");
3359
3434
  if (values.yes !== true) fail(`logging a session on ${date} writes to your coach-visible log; add --yes.`);
3360
- return out(await logAdHocSession(client, {
3435
+ const result = await logAdHocSession(client, {
3361
3436
  date: args.date,
3362
3437
  exercises: toSessionExercises(args.exercises)
3363
- }));
3438
+ });
3439
+ const scheduled = result.scheduledAlternatives ?? [];
3440
+ if (scheduled.length > 0) {
3441
+ const names = scheduled.map((s) => s.title).join(", ");
3442
+ process.stderr.write(`note: ${names} ${scheduled.length === 1 ? "was" : "were"} already on a coach-scheduled workout today; this logged a SEPARATE personal session. To log into the scheduled workout instead, use 'athlete log-set' with the savedWorkoutSetId/savedWorkoutSetExerciseId in scheduledAlternatives, or 'athlete session-remove' to delete this personal session.\n`);
3443
+ }
3444
+ return out(result);
3445
+ }
3446
+ async function cmdAthleteLogTargets(client, a) {
3447
+ const usage = "athlete log-targets --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw]";
3448
+ const { values } = parse(a, {
3449
+ start: { type: "string" },
3450
+ end: { type: "string" },
3451
+ program: { type: "string" },
3452
+ "program-id": { type: "string" },
3453
+ team: { type: "string" },
3454
+ raw: { type: "boolean" }
3455
+ });
3456
+ const all = await fetchAthleteWorkouts(client, isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3457
+ const filter = {};
3458
+ if (values.program !== void 0) filter.programTitle = values.program;
3459
+ if (values["program-id"] !== void 0) filter.programId = toInt(values["program-id"], "--program-id");
3460
+ if (values.team !== void 0) filter.teamId = toInt(values.team, "--team");
3461
+ const workouts = selectWorkoutsByProgram(all, filter);
3462
+ return out(values.raw === true ? workouts : presentLogTargets(workouts));
3463
+ }
3464
+ const SESSION_REMOVE_USAGE = "athlete session-remove --id <programWorkoutId> --date Y-M-D --yes";
3465
+ async function cmdAthleteSessionRemove(client, a) {
3466
+ const { values } = parse(a, {
3467
+ id: { type: "string" },
3468
+ date: { type: "string" },
3469
+ yes: { type: "boolean" }
3470
+ });
3471
+ const args = validate(athleteSessionRemoveArgsSchema, {
3472
+ programWorkoutId: need(values.id, SESSION_REMOVE_USAGE),
3473
+ date: isoDate(need(values.date, SESSION_REMOVE_USAGE), "--date")
3474
+ }, "session-remove args");
3475
+ const id = toInt(String(args.programWorkoutId), "--id");
3476
+ if (values.yes !== true) fail(`removing personal session ${id} deletes its logged work; add --yes.`);
3477
+ await removePersonalWorkout(client, {
3478
+ programWorkoutId: id,
3479
+ date: args.date
3480
+ });
3481
+ return out({
3482
+ removed: true,
3483
+ programWorkoutId: id,
3484
+ date: args.date
3485
+ });
3364
3486
  }
3365
3487
  async function cmdAthlete(client, rest) {
3366
3488
  const [sub, ...a] = rest;
@@ -3431,9 +3553,11 @@ async function cmdAthlete(client, rest) {
3431
3553
  return out(await fetchLeaderboard(client, workoutId, opts));
3432
3554
  }
3433
3555
  case "export": return cmdAthleteExport(client, a);
3556
+ case "log-targets": return cmdAthleteLogTargets(client, a);
3434
3557
  case "log-set": return cmdAthleteLogSet(client, a);
3435
3558
  case "log-session": return cmdAthleteLogSession(client, a);
3436
- default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session>");
3559
+ case "session-remove": return cmdAthleteSessionRemove(client, a);
3560
+ default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|log-targets|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session|session-remove>");
3437
3561
  }
3438
3562
  }
3439
3563
  async function cmdSkill(rest) {
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/alandotcom/trainheroic-unofficial.git",
8
8
  "directory": "packages/cli"
9
9
  },
10
- "description": "Command-line tool for the TrainHeroic coaching API.",
10
+ "description": "Command-line tool for the TrainHeroic API.",
11
11
  "type": "module",
12
12
  "bin": {
13
13
  "trainheroic": "./dist/cli.mjs"
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.5.0",
25
- "@trainheroic-unofficial/js": "1.5.0"
24
+ "@trainheroic-unofficial/dto": "1.6.0",
25
+ "@trainheroic-unofficial/js": "1.6.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",
@@ -63,8 +63,10 @@ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`.
63
63
  | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
64
  | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
65
65
  | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
+ | Log ids for a scheduled workout | `$TH athlete log-targets --start Y-M-D --end Y-M-D [--program <title>]` |
66
67
  | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
67
68
  | Log an off-plan session (gated) | `$TH athlete log-session --date Y-M-D '[{"exerciseId":N,"sets":[...]}]' --yes` |
69
+ | Remove a stray personal session | `$TH athlete session-remove --id <programWorkoutId> --date Y-M-D --yes` |
68
70
 
69
71
  ## Reading training
70
72
 
@@ -114,11 +116,12 @@ marks the set completed, and the result shows up in your exercise history. **It
114
116
  athlete-facing**: it mutates your training log, which your coach can see, so confirm before
115
117
  running and re-read the workout to check the result landed.
116
118
 
117
- Get the `savedWorkoutSetId` and each `savedWorkoutSetExerciseId` from the raw workout
118
- (`$TH athlete workouts --start <day> --end <day> --raw`, under
119
- `summarizedSavedWorkout.saved_workout.workoutSets`). Then:
119
+ Get the `savedWorkoutSetId` and each `savedWorkoutSetExerciseId` from `$TH athlete log-targets`
120
+ — a compact one-row-per-set view, no raw blob to dig through. When several workouts fall on the
121
+ same day (you're on more than one program), narrow with `--program <title-substring>`:
120
122
 
121
123
  ```bash
124
+ $TH athlete log-targets --start 2026-06-01 --end 2026-06-01 --program "Bodybuilding"
122
125
  $TH athlete log-set --date 2026-06-01 --set 1593305783 --yes \
123
126
  '[{"savedWorkoutSetExerciseId": 2712369448, "sets": [{"param1": 3, "param2": 225}]}]'
124
127
  ```
@@ -8,7 +8,7 @@ metadata:
8
8
 
9
9
  # TrainHeroic API
10
10
 
11
- Authenticated access to the TrainHeroic coaching API through the `trainheroic`
11
+ Authenticated access to the TrainHeroic API through the `trainheroic`
12
12
  command-line tool (`@trainheroic-unofficial/cli`), which wraps the `@trainheroic-unofficial/js`
13
13
  SDK: a spec-driven workout builder, an on-disk exercise cache, and gated messaging.
14
14