@trainheroic-unofficial/cli 1.3.0 → 1.5.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.
Files changed (2) hide show
  1. package/dist/cli.mjs +236 -76
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -163,16 +163,29 @@ const loggedSetSchema = z.object({
163
163
  param2: z.union([z.number(), z.string()]).optional()
164
164
  });
165
165
  /**
166
+ * A logged set that can name the prescribed position it fills. `slot` is the 1-based set
167
+ * index in the prescription (10 max) the result should land in; omit it to fill the next
168
+ * sequential position (the first entry is set 1, the second set 2, and so on). Targeting a
169
+ * slot lets a partial log land in the right positions of a multi-set prescription — e.g.
170
+ * three top singles into the 4th/5th/6th positions of an `8,5,3,1,1,1` ramp. Used by the
171
+ * by-set logging write (not the by-exercise session log, where each exercise's sets are
172
+ * always sequential).
173
+ */
174
+ const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().min(1).max(10).optional() });
175
+ /**
166
176
  * Args for the set-logging write. `date` (the workout's day) locates the saved
167
177
  * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
168
- * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
178
+ * gives, per exercise in it, the entered value of each set. Each set fills the next position by
179
+ * default, or names its `slot` (1-based) to place a partial log at specific positions. A partial
180
+ * log keeps positions already logged in an earlier call and leaves the positions it does not
181
+ * write empty.
169
182
  */
170
183
  const logSetArgsSchema = z.object({
171
184
  date: dateString,
172
185
  savedWorkoutSetId: idArgSchema,
173
186
  results: z.array(z.object({
174
187
  savedWorkoutSetExerciseId: idArgSchema,
175
- sets: z.array(loggedSetSchema).min(1)
188
+ sets: z.array(loggedSetWithSlotSchema).min(1)
176
189
  })).min(1)
177
190
  });
178
191
  /**
@@ -181,14 +194,23 @@ const logSetArgsSchema = z.object({
181
194
  */
182
195
  const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
196
  /**
184
- * Args for the coach prescription-override write. Structurally the same as
185
- * {@link coachLogSetArgsSchema} (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but
186
- * the values are prescribed targets (param1 = reps, param2 = weight) written to the athlete's
187
- * plan without marking the set performed. It is a separate schema (not an alias) so a future
188
- * prescribe-only constraint can be added here without changing the log args, and the write
189
- * replaces the slot's prescribed values for this athlete only.
197
+ * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
198
+ * (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but the values are prescribed
199
+ * targets (param1 = reps, param2 = weight) written to the athlete's plan without marking the set
200
+ * performed. The write replaces this athlete's whole prescription for the set, so its sets are
201
+ * positional and sequential by definition: it deliberately omits the log path's `slot` field (a
202
+ * sparse, slot-targeted prescription has no meaning here) by building its results off
203
+ * {@link loggedSetSchema} rather than {@link loggedSetWithSlotSchema}.
190
204
  */
191
- const coachPrescribeSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
205
+ const coachPrescribeSetArgsSchema = z.object({
206
+ date: dateString,
207
+ savedWorkoutSetId: idArgSchema,
208
+ athleteId: idArgSchema,
209
+ results: z.array(z.object({
210
+ savedWorkoutSetExerciseId: idArgSchema,
211
+ sets: z.array(loggedSetSchema).min(1)
212
+ })).min(1)
213
+ });
192
214
  /**
193
215
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
194
216
  * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
@@ -319,7 +341,20 @@ function parseWorkoutDate(s) {
319
341
  }
320
342
  //#endregion
321
343
  //#region ../js/src/auth.ts
322
- const AUTH_URL = "https://apis.trainheroic.com/auth";
344
+ const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
345
+ /**
346
+ * The login endpoint, allowing an env override so a test harness can authenticate against a local
347
+ * fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
348
+ * the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
349
+ * (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
350
+ */
351
+ function authUrl() {
352
+ const env = globalThis.process?.env;
353
+ if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
354
+ const apis = env?.TH_APIS_BASE;
355
+ if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
356
+ return DEFAULT_AUTH_URL;
357
+ }
323
358
  /**
324
359
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
325
360
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
@@ -327,7 +362,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
327
362
  * is sent as the `session-token` header and works against both API hosts.
328
363
  */
329
364
  async function loginTrainHeroic(email, password) {
330
- const res = await fetch(AUTH_URL, {
365
+ const res = await fetch(authUrl(), {
331
366
  method: "POST",
332
367
  headers: {
333
368
  "content-type": "application/x-www-form-urlencoded",
@@ -350,8 +385,19 @@ async function loginTrainHeroic(email, password) {
350
385
  }
351
386
  //#endregion
352
387
  //#region ../js/src/client.ts
353
- const COACH_BASE = "https://api.trainheroic.com";
354
- const APIS_BASE = "https://apis.trainheroic.com";
388
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
389
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
390
+ /**
391
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
392
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
393
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
394
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
395
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
396
+ */
397
+ function envBase(key, fallback) {
398
+ const v = (globalThis.process?.env)?.[key];
399
+ return v && v.length > 0 ? v : fallback;
400
+ }
355
401
  var TrainHeroicAuthError = class extends Error {
356
402
  name = "TrainHeroicAuthError";
357
403
  };
@@ -390,7 +436,7 @@ var TrainHeroicClient = class {
390
436
  return this.#sessionId;
391
437
  }
392
438
  async request(method, path, options = {}) {
393
- const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
439
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
394
440
  let session = await this.#ensureSession();
395
441
  let res = await this.#send(method, url, session, options.body);
396
442
  if (res.status === 401 || res.status === 403) {
@@ -559,6 +605,10 @@ function asExerciseList(body) {
559
605
  function isRecord(x) {
560
606
  return typeof x === "object" && x !== null && !Array.isArray(x);
561
607
  }
608
+ /** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
609
+ function str$1(v) {
610
+ return typeof v === "string" && v !== "" ? v : null;
611
+ }
562
612
  /**
563
613
  * Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
564
614
  * exact title, then prefix, then count of matched tokens, with shorter titles and
@@ -738,7 +788,6 @@ function fetchLeaderboard(client, workoutId, opts = {}) {
738
788
  const query = qs.toString();
739
789
  return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
740
790
  }
741
- const SLOTS = 10;
742
791
  function nonEmpty(value) {
743
792
  return value !== void 0 && value !== null && String(value).trim() !== "";
744
793
  }
@@ -749,7 +798,7 @@ function nonEmpty(value) {
749
798
  */
750
799
  function prescribedSets(ex) {
751
800
  const out = [];
752
- for (let i = 1; i <= SLOTS; i += 1) {
801
+ for (let i = 1; i <= 10; i += 1) {
753
802
  const p1 = ex[`param_1_data_${i}`];
754
803
  const p2 = ex[`param_2_data_${i}`];
755
804
  const has1 = nonEmpty(p1);
@@ -770,7 +819,7 @@ function prescribedSets(ex) {
770
819
  */
771
820
  function performedSets(ex) {
772
821
  const out = [];
773
- for (let i = 1; i <= SLOTS; i += 1) {
822
+ for (let i = 1; i <= 10; i += 1) {
774
823
  if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
775
824
  const p1 = ex[`param_1_data_${i}`];
776
825
  const p2 = ex[`param_2_data_${i}`];
@@ -804,9 +853,6 @@ function presentBlock(set, performedById) {
804
853
  exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
805
854
  };
806
855
  }
807
- function str$1(v) {
808
- return typeof v === "string" && v !== "" ? v : null;
809
- }
810
856
  /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
811
857
  function savedSets(saved) {
812
858
  const out = [];
@@ -904,12 +950,35 @@ function presentAthleteWorkouts(list) {
904
950
  return list.map(presentAthleteWorkout);
905
951
  }
906
952
  /**
953
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
954
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
955
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
956
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
957
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
958
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
959
+ */
960
+ function selectWorkoutsByProgram(list, filter) {
961
+ const { programId, teamId, programTitle } = filter;
962
+ const needle = programTitle?.trim().toLowerCase();
963
+ if (programId === void 0 && teamId === void 0 && !needle) return [...list];
964
+ return list.filter((pw) => {
965
+ const rec = pw;
966
+ if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
967
+ if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
968
+ if (needle) {
969
+ if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
970
+ }
971
+ return false;
972
+ });
973
+ }
974
+ /**
907
975
  * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
908
976
  * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
909
977
  * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
910
978
  * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
911
- * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
912
- * with no resolvable id.
979
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
980
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
981
+ * dropping any set with no resolvable id.
913
982
  */
914
983
  function presentLogTargets(list) {
915
984
  const targets = [];
@@ -920,6 +989,10 @@ function presentLogTargets(list) {
920
989
  if (!saved) continue;
921
990
  const date = str$1(rec.date) ?? "";
922
991
  const workoutTitle = str$1(rec.workout_title) ?? "";
992
+ const program = str$1(rec.program_title);
993
+ const programId = coerceInt(rec.program_id);
994
+ const team = str$1(rec.team_title);
995
+ const teamId = coerceInt(rec.team_id);
923
996
  const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
924
997
  for (const s of sets) {
925
998
  if (!isRecord(s)) continue;
@@ -939,6 +1012,10 @@ function presentLogTargets(list) {
939
1012
  targets.push({
940
1013
  date,
941
1014
  workoutTitle,
1015
+ program,
1016
+ programId,
1017
+ team,
1018
+ teamId,
942
1019
  savedWorkoutSetId,
943
1020
  setTitle: str$1(s.title),
944
1021
  exercises
@@ -1028,7 +1105,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1028
1105
  sessions
1029
1106
  };
1030
1107
  }
1031
- const MAX_PARAM_SLOTS = 10;
1108
+ /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1109
+ function presentExerciseHistory(detail) {
1110
+ return {
1111
+ liftPRs: (detail.liftPRs ?? []).map((p) => ({
1112
+ description: p.description ?? null,
1113
+ reps: p.reps ?? null,
1114
+ weight: p.weight ?? null,
1115
+ units: p.units ?? null,
1116
+ date: p.dateCompleted ?? null
1117
+ })),
1118
+ sessions: (detail.history ?? []).map((h) => ({
1119
+ date: h.dateCompleted,
1120
+ abr: h.abr ?? null,
1121
+ estimated1RM: h.bestEstimated1RM ?? null,
1122
+ sets: (h.sets ?? []).map((s) => ({
1123
+ setNumber: s.setNumber,
1124
+ value: s.formattedValue ?? null
1125
+ }))
1126
+ }))
1127
+ };
1128
+ }
1129
+ //#endregion
1130
+ //#region ../js/src/athlete-set-write.ts
1032
1131
  /**
1033
1132
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1034
1133
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1043,10 +1142,11 @@ function toSetResults(results) {
1043
1142
  return {
1044
1143
  savedWorkoutSetExerciseId: id,
1045
1144
  sets: r.sets.map((s) => {
1046
- const slot = {};
1047
- if (s.param1 !== void 0) slot.param1 = s.param1;
1048
- if (s.param2 !== void 0) slot.param2 = s.param2;
1049
- return slot;
1145
+ const set = {};
1146
+ if (s.param1 !== void 0) set.param1 = s.param1;
1147
+ if (s.param2 !== void 0) set.param2 = s.param2;
1148
+ if (s.slot !== void 0) set.slot = s.slot;
1149
+ return set;
1050
1150
  })
1051
1151
  };
1052
1152
  });
@@ -1058,36 +1158,96 @@ function toSetResults(results) {
1058
1158
  *
1059
1159
  * `mode` selects which write this is — the same endpoint serves both:
1060
1160
  * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1061
- * and the exercise `completed` flag is 1 when any set has data.
1161
+ * and the exercise `completed` flag is 1 when any set has logged data.
1062
1162
  * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1063
1163
  * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1064
1164
  * coach edits an athlete's prescribed reps/weight.
1065
1165
  *
1166
+ * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1167
+ * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1168
+ * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1169
+ * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1170
+ * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1171
+ * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1172
+ * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1173
+ * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1174
+ *
1066
1175
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1067
- * required from the live exercise record; everything else is derived from `results`.
1176
+ * required from the live exercise record; everything else is derived from `results` and the
1177
+ * preserved slots of `existing`.
1068
1178
  *
1069
1179
  * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1070
1180
  */
1071
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1072
- if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1181
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1182
+ if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1183
+ const bySlot = /* @__PURE__ */ new Map();
1184
+ results.forEach((set, i) => {
1185
+ const slot = set.slot ?? i + 1;
1186
+ if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1187
+ if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1188
+ bySlot.set(slot, set);
1189
+ });
1073
1190
  const performed = mode === "log";
1074
- const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1191
+ const carryOver = performed && existing !== void 0;
1075
1192
  const body = {
1076
1193
  id: savedWorkoutSetExerciseId,
1077
1194
  saved_workout_set_id: savedWorkoutSetId,
1078
- workout_set_exercise_id: workoutSetExerciseId,
1079
- completed: performed && hasData ? 1 : 0
1195
+ workout_set_exercise_id: workoutSetExerciseId
1080
1196
  };
1081
- for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1082
- const slot = results[i - 1];
1083
- const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1084
- const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1085
- body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1197
+ let anyMade = false;
1198
+ for (let i = 1; i <= 10; i += 1) {
1199
+ const target = bySlot.get(i);
1200
+ let p1;
1201
+ let p2;
1202
+ let made;
1203
+ if (target) {
1204
+ p1 = target.param1 !== void 0 ? String(target.param1) : "";
1205
+ p2 = target.param2 !== void 0 ? String(target.param2) : "";
1206
+ made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1207
+ } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1208
+ p1 = existingSlotData(existing, `param_1_data_${i}`);
1209
+ p2 = existingSlotData(existing, `param_2_data_${i}`);
1210
+ made = 1;
1211
+ } else {
1212
+ p1 = "";
1213
+ p2 = "";
1214
+ made = 0;
1215
+ }
1216
+ if (made === 1) anyMade = true;
1217
+ body[`param_${i}_made`] = made;
1086
1218
  body[`param_1_data_${i}`] = p1;
1087
1219
  body[`param_2_data_${i}`] = p2;
1088
1220
  }
1221
+ body.completed = performed && anyMade ? 1 : 0;
1089
1222
  return body;
1090
1223
  }
1224
+ /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1225
+ function existingSlotData(existing, key) {
1226
+ const v = existing?.[key];
1227
+ return v === void 0 || v === null ? "" : String(v);
1228
+ }
1229
+ /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1230
+ function exerciseHasLoggedData(ex) {
1231
+ for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1232
+ return false;
1233
+ }
1234
+ /** True when a result carries at least one non-empty param value (so it produces a performed slot). */
1235
+ function resultHasData(result) {
1236
+ return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
1237
+ }
1238
+ /**
1239
+ * Whether every exercise in a saved workout set now has logged data — either written with data in
1240
+ * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1241
+ * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1242
+ * does not flip its still-empty siblings to "done". An exercise written with only empty values does
1243
+ * not count (it would not be marked performed), so an all-empty log never completes the set.
1244
+ */
1245
+ function isSetFullyLogged(exercises, loggedIds) {
1246
+ return exercises.every((ex) => {
1247
+ const id = coerceInt(ex.id);
1248
+ return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1249
+ });
1250
+ }
1091
1251
  /**
1092
1252
  * Locate the target saved workout set across all program workouts on the given day.
1093
1253
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1186,7 +1346,8 @@ async function logAthleteSet(client, args) {
1186
1346
  const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1187
1347
  return {
1188
1348
  savedWorkoutSetId: r.savedWorkoutSetId,
1189
- exercisesLogged: r.exercisesWritten
1349
+ exercisesLogged: r.exercisesWritten,
1350
+ setCompleted: r.setCompleted
1190
1351
  };
1191
1352
  }
1192
1353
  /**
@@ -1207,7 +1368,8 @@ async function logForAthlete(client, args) {
1207
1368
  }, workouts, args.savedWorkoutSetId, args.results, "log");
1208
1369
  return {
1209
1370
  savedWorkoutSetId: r.savedWorkoutSetId,
1210
- exercisesLogged: r.exercisesWritten
1371
+ exercisesLogged: r.exercisesWritten,
1372
+ setCompleted: r.setCompleted
1211
1373
  };
1212
1374
  }
1213
1375
  /**
@@ -1300,9 +1462,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1300
1462
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1301
1463
  }
1302
1464
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1303
- if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1465
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
1304
1466
  const body = {
1305
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1467
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1306
1468
  ...extra
1307
1469
  };
1308
1470
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
@@ -1312,17 +1474,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1312
1474
  }
1313
1475
  exercisesWritten += 1;
1314
1476
  }
1477
+ let setCompleted = false;
1315
1478
  if (mode === "log") {
1316
- const setBody = {
1317
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1318
- ...extra
1319
- };
1320
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1321
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1479
+ if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
1480
+ const setBody = {
1481
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1482
+ ...extra
1483
+ };
1484
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1485
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1486
+ setCompleted = true;
1487
+ }
1322
1488
  }
1323
1489
  return {
1324
1490
  savedWorkoutSetId,
1325
- exercisesWritten
1491
+ exercisesWritten,
1492
+ setCompleted
1326
1493
  };
1327
1494
  }
1328
1495
  /**
@@ -1479,7 +1646,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1479
1646
  savedWorkoutSetId,
1480
1647
  results
1481
1648
  });
1482
- out.push(written);
1649
+ out.push({
1650
+ savedWorkoutSetId: written.savedWorkoutSetId,
1651
+ exercisesLogged: written.exercisesLogged
1652
+ });
1483
1653
  }
1484
1654
  return out;
1485
1655
  }
@@ -1557,27 +1727,6 @@ async function logSessionForAthlete(client, args) {
1557
1727
  sets
1558
1728
  };
1559
1729
  }
1560
- /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1561
- function presentExerciseHistory(detail) {
1562
- return {
1563
- liftPRs: (detail.liftPRs ?? []).map((p) => ({
1564
- description: p.description ?? null,
1565
- reps: p.reps ?? null,
1566
- weight: p.weight ?? null,
1567
- units: p.units ?? null,
1568
- date: p.dateCompleted ?? null
1569
- })),
1570
- sessions: (detail.history ?? []).map((h) => ({
1571
- date: h.dateCompleted,
1572
- abr: h.abr ?? null,
1573
- estimated1RM: h.bestEstimated1RM ?? null,
1574
- sets: (h.sets ?? []).map((s) => ({
1575
- setNumber: s.setNumber,
1576
- value: s.formattedValue ?? null
1577
- }))
1578
- }))
1579
- };
1580
- }
1581
1730
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1582
1731
  function emailList(emails) {
1583
1732
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2758,7 +2907,7 @@ Coach — manage a roster (needs a coach account):
2758
2907
  roster athlete reads (three lenses — pick by the question):
2759
2908
  coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
2760
2909
  coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D team training volume scoped to a date window: per-athlete rows (only those who logged in range) + rolled-up totals (volume in lb). --team resolves the roster; --athletes passes ids directly.
2761
- coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2910
+ coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --program (title substring) / --program-id / --team targets one program when the athlete is on several; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2762
2911
  coach athlete-training --athlete <id> --year <YYYY> --month <1-12> sessions the athlete LOGGED in one month (empty = nothing logged that month, not an error)
2763
2912
  coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
2764
2913
  coach main-lift-prs [--athlete <id>] [--athletes <id,id,...>] [--months <n>] best PRs for the main lifts (squat/bench/deadlift/overhead press/clean & jerk/snatch); auto-discovers the logged variant. With --athlete, one athlete; otherwise the whole roster (or --athletes subset)
@@ -2768,6 +2917,9 @@ Coach — manage a roster (needs a coach account):
2768
2917
  --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2769
2918
  and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2770
2919
  resultsJson: [{"savedWorkoutSetExerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2920
+ each set fills the next position; add "slot":K to place it at the K-th prescribed set. A
2921
+ partial log records only the positions you send (plus any logged earlier); a superset block
2922
+ completes only once all its exercises are logged.
2771
2923
  coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2772
2924
  log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2773
2925
  already on the athlete's calendar that day. The API can't put an off-plan session on an
@@ -2840,7 +2992,7 @@ Athlete — the logged-in user's own training (a coach account works too):
2840
2992
  athlete stats <exerciseId> --date Y-M-D
2841
2993
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2842
2994
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2843
- 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')
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)
2844
2996
  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')
2845
2997
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2846
2998
  `;
@@ -3437,18 +3589,26 @@ async function cmdCoachTeamVolume(client, a) {
3437
3589
  }));
3438
3590
  }
3439
3591
  async function cmdCoachAthleteWorkouts(client, a) {
3440
- const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
3592
+ const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
3441
3593
  const { values } = parse(a, {
3442
3594
  athlete: { type: "string" },
3443
3595
  start: { type: "string" },
3444
3596
  end: { type: "string" },
3597
+ program: { type: "string" },
3598
+ "program-id": { type: "string" },
3599
+ team: { type: "string" },
3445
3600
  raw: { type: "boolean" },
3446
3601
  "log-ids": { type: "boolean" },
3447
3602
  "logged-only": { type: "boolean" },
3448
3603
  limit: { type: "string" },
3449
3604
  summary: { type: "boolean" }
3450
3605
  });
3451
- const workouts = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3606
+ const all = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3607
+ const filter = {};
3608
+ if (values.program !== void 0) filter.programTitle = values.program;
3609
+ if (values["program-id"] !== void 0) filter.programId = toInt(values["program-id"], "--program-id");
3610
+ if (values.team !== void 0) filter.teamId = toInt(values.team, "--team");
3611
+ const workouts = selectWorkoutsByProgram(all, filter);
3452
3612
  if (values["log-ids"] === true) return out(presentLogTargets(workouts));
3453
3613
  if (values.raw === true) return out(workouts);
3454
3614
  const opts = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.3.0",
25
- "@trainheroic-unofficial/js": "1.3.0"
24
+ "@trainheroic-unofficial/dto": "1.5.0",
25
+ "@trainheroic-unofficial/js": "1.5.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",