@trainheroic-unofficial/cli 1.6.1 → 1.7.1

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/cli.mjs CHANGED
@@ -564,7 +564,7 @@ function withUnits(row) {
564
564
  * Present a full raw exercise object for display: drop the raw param-type codes and add the
565
565
  * positional `units` array. Keeps every other field of the raw object intact.
566
566
  */
567
- function presentExercise$1(raw) {
567
+ function presentExercise(raw) {
568
568
  const { param_1_type, param_2_type, ...rest } = raw;
569
569
  return {
570
570
  ...rest,
@@ -788,6 +788,66 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
788
788
  function fetchAthleteWorkouts(client, startDate, endDate) {
789
789
  return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
790
790
  }
791
+ /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
792
+ function shiftDate(iso, days) {
793
+ const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
794
+ d.setUTCDate(d.getUTCDate() + days);
795
+ return d.toISOString().slice(0, 10);
796
+ }
797
+ /** Split an inclusive `[start, end]` range into consecutive non-overlapping windows of `windowDays`. */
798
+ function dateWindows(startDate, endDate, windowDays) {
799
+ const size = Math.max(1, Math.floor(windowDays));
800
+ const windows = [];
801
+ let cursor = startDate;
802
+ while (cursor <= endDate) {
803
+ const winEnd = shiftDate(cursor, size - 1);
804
+ const clamped = winEnd > endDate ? endDate : winEnd;
805
+ windows.push({
806
+ start: cursor,
807
+ end: clamped
808
+ });
809
+ cursor = shiftDate(clamped, 1);
810
+ }
811
+ return windows;
812
+ }
813
+ /**
814
+ * Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
815
+ * window boundary must not double up, first occurrence wins), then sorted oldest-first by date so
816
+ * the order is stable regardless of window seams. Id-less rows are kept and appended.
817
+ */
818
+ function mergeWorkoutsById(pages) {
819
+ const byId = /* @__PURE__ */ new Map();
820
+ const noId = [];
821
+ for (const pw of pages.flat()) {
822
+ const id = coerceInt(pw.id);
823
+ if (id === null) noId.push(pw);
824
+ else if (!byId.has(id)) byId.set(id, pw);
825
+ }
826
+ return [...byId.values(), ...noId].sort((a, b) => {
827
+ const da = str$1(a.date) ?? "";
828
+ const db = str$1(b.date) ?? "";
829
+ return da < db ? -1 : da > db ? 1 : 0;
830
+ });
831
+ }
832
+ /**
833
+ * Fetch an athlete's workouts across a long range by splitting it into windows and fetching them
834
+ * with bounded concurrency, then merging (deduped by workout id, sorted oldest-first). The
835
+ * `programworkout/range` endpoint 504s on a multi-year span, so a full-history export must chunk.
836
+ * `windowDays` defaults to 180; `onProgress(done, total)` reports completed windows for a progress
837
+ * indicator. A range that fits one window delegates to the plain fetch (API order preserved).
838
+ */
839
+ async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}) {
840
+ const windows = dateWindows(startDate, endDate, opts.windowDays ?? 180);
841
+ if (windows.length <= 1) return fetchAthleteWorkouts(client, startDate, endDate);
842
+ let done = 0;
843
+ const total = windows.length;
844
+ return mergeWorkoutsById(await mapPool(windows, opts.concurrency ?? 4, async (w) => {
845
+ const page = await fetchAthleteWorkouts(client, w.start, w.end);
846
+ done += 1;
847
+ opts.onProgress?.(done, total);
848
+ return page;
849
+ }));
850
+ }
791
851
  /**
792
852
  * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
793
853
  * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
@@ -818,66 +878,40 @@ function nonEmpty(value) {
818
878
  return value !== void 0 && value !== null && String(value).trim() !== "";
819
879
  }
820
880
  /**
821
- * Per-set prescriptions from the param_N_data slots, e.g. ["5 @ 225", "3 @ 245"] or ["AMRAP"].
822
- * Values are kept raw (a non-numeric prescription like "AMRAP" or "8-12" must survive); the
823
- * positional units come from the exercise's param types, mirroring the coach presenter.
881
+ * Slot-indexed values for one exercise. With `requireMade`, only slots the athlete logged
882
+ * (`param_i_made === 1`) — the performed reader; otherwise every slot carrying data — the
883
+ * prescription reader. Values stay raw; the projectors format or parse them.
824
884
  */
825
- function prescribedSets(ex) {
826
- const out = [];
885
+ function slotValues(ex, requireMade) {
886
+ const map = /* @__PURE__ */ new Map();
827
887
  for (let i = 1; i <= 10; i += 1) {
888
+ if (requireMade && coerceInt(ex[`param_${i}_made`]) !== 1) continue;
828
889
  const p1 = ex[`param_1_data_${i}`];
829
890
  const p2 = ex[`param_2_data_${i}`];
830
- const has1 = nonEmpty(p1);
831
- const has2 = nonEmpty(p2);
832
- if (!has1 && !has2) continue;
833
- if (has1 && has2) out.push(`${p1} @ ${p2}`);
834
- else if (has1) out.push(String(p1));
835
- else out.push(`@ ${p2}`);
891
+ if (!nonEmpty(p1) && !nonEmpty(p2)) continue;
892
+ map.set(i, {
893
+ p1: nonEmpty(p1) ? p1 : null,
894
+ p2: nonEmpty(p2) ? p2 : null
895
+ });
836
896
  }
837
- return out;
897
+ return map;
838
898
  }
839
- /**
840
- * The per-set values the athlete actually logged, read from a saved-copy exercise. A set
841
- * counts as performed only when its `param_{i}_made` flag is 1: the saved copy pre-fills the
842
- * `param_N_data` slots with the prescription, so the presence of data alone does not mean a
843
- * set was done. `param_{i}_made` is the same per-set flag the logging write sets, and is the
844
- * only reliable signal (the `completed` flags are often left at 0 on a logged session).
845
- */
846
- function performedSets(ex) {
847
- const out = [];
848
- for (let i = 1; i <= 10; i += 1) {
849
- if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
850
- const p1 = ex[`param_1_data_${i}`];
851
- const p2 = ex[`param_2_data_${i}`];
852
- const has1 = nonEmpty(p1);
853
- const has2 = nonEmpty(p2);
854
- if (has1 && has2) out.push(`${p1} @ ${p2}`);
855
- else if (has1) out.push(String(p1));
856
- else if (has2) out.push(`@ ${p2}`);
857
- }
858
- return out;
899
+ /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
900
+ function fmtSlot(slot) {
901
+ const has1 = slot.p1 !== null;
902
+ const has2 = slot.p2 !== null;
903
+ if (has1 && has2) return `${slot.p1} @ ${slot.p2}`;
904
+ if (has1) return String(slot.p1);
905
+ if (has2) return `@ ${slot.p2}`;
906
+ return "";
859
907
  }
860
- function presentExercise(ex, performedById) {
861
- const instruction = typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null;
862
- const id = coerceInt(ex.id);
863
- return {
864
- exerciseId: coerceInt(ex.exercise_id),
865
- title: typeof ex.title === "string" ? ex.title : "",
866
- instruction,
867
- units: exerciseUnits(ex.param_1_type, ex.param_2_type),
868
- prescribed: prescribedSets(ex),
869
- performed: (id !== null ? performedById.get(id) : void 0) ?? []
870
- };
908
+ /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
909
+ function prescribedStrings(ex) {
910
+ return [...slotValues(ex, false).values()].map(fmtSlot);
871
911
  }
872
- function presentBlock(set, performedById) {
873
- const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
874
- return {
875
- order: coerceInt(set.order) ?? 0,
876
- title: typeof set.title === "string" && set.title !== "" ? set.title : null,
877
- instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
878
- isTest: coerceInt(set.is_test) === 1,
879
- exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
880
- };
912
+ /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
913
+ function performedStrings(ex) {
914
+ return [...slotValues(ex, true).values()].map(fmtSlot);
881
915
  }
882
916
  /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
883
917
  function savedSets(saved) {
@@ -896,54 +930,82 @@ function savedSets(saved) {
896
930
  return out;
897
931
  }
898
932
  /**
899
- * Map each prescription exercise id to the per-set values the athlete logged. In the saved
900
- * copy, `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
901
- * entered values live in the same `param_N_data` slots as a prescription — so the
902
- * prescription reader works on them unchanged.
933
+ * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
934
+ * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
935
+ * entered values live in the same `param_N_data` slots as a prescription.
903
936
  */
904
- function performedByExerciseId(sets) {
937
+ function performedSlotsByExerciseId(sets) {
905
938
  const map = /* @__PURE__ */ new Map();
906
939
  for (const { exercises } of sets) for (const ex of exercises) {
907
940
  const id = coerceInt(ex.workout_set_exercise_id);
908
941
  if (id === null) continue;
909
- const values = performedSets(ex);
910
- if (values.length > 0) map.set(id, values);
942
+ const slots = slotValues(ex, true);
943
+ if (slots.size > 0) map.set(id, slots);
911
944
  }
912
945
  return map;
913
946
  }
914
- /** Present a logged set straight from the saved copy (athlete-added or personal work). */
915
- function presentSavedBlock(set, exercises) {
947
+ /** Align an exercise's prescribed slots with the slots the athlete logged, per set index. */
948
+ function mergeExercise(prescribed, performed, meta) {
949
+ const indices = [.../* @__PURE__ */ new Set([...prescribed.keys(), ...performed.keys()])].sort((a, b) => a - b);
950
+ return {
951
+ ...meta,
952
+ sets: indices.map((i) => ({
953
+ set: i,
954
+ prescribed: prescribed.get(i) ?? null,
955
+ performed: performed.get(i) ?? null
956
+ }))
957
+ };
958
+ }
959
+ /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
960
+ function mergePrescriptionBlock(set, performedById) {
961
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
916
962
  return {
917
963
  order: coerceInt(set.order) ?? 0,
918
- title: typeof set.title === "string" && set.title !== "" ? set.title : null,
919
- instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
964
+ title: str$1(set.title),
965
+ instruction: str$1(set.instruction),
920
966
  isTest: coerceInt(set.is_test) === 1,
921
- exercises: exercises.map((ex) => ({
967
+ exercises: exercises.filter(isRecord).map((ex) => {
968
+ const id = coerceInt(ex.id);
969
+ const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
970
+ return mergeExercise(slotValues(ex, false), performed, {
971
+ exerciseId: coerceInt(ex.exercise_id),
972
+ title: typeof ex.title === "string" ? ex.title : "",
973
+ instruction: str$1(ex.instruction),
974
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type)
975
+ });
976
+ })
977
+ };
978
+ }
979
+ /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
980
+ function mergeSavedBlock(set, exercises) {
981
+ return {
982
+ order: coerceInt(set.order) ?? 0,
983
+ title: str$1(set.title),
984
+ instruction: str$1(set.instruction),
985
+ isTest: coerceInt(set.is_test) === 1,
986
+ exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
922
987
  exerciseId: coerceInt(ex.exercise_id),
923
988
  title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
924
- instruction: typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null,
925
- units: exerciseUnits(ex.param_1_type, ex.param_2_type),
926
- prescribed: [],
927
- performed: performedSets(ex)
989
+ instruction: str$1(ex.instruction),
990
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type)
928
991
  }))
929
992
  };
930
993
  }
931
994
  /**
932
- * Flatten one `/3.0/athlete/programworkout/range` item into a readable workout, merging the
995
+ * Flatten one `/3.0/athlete/programworkout/range` item into the canonical merged form, joining the
933
996
  * prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
934
- * (`summarizedSavedWorkout.saved_workout`). Each exercise carries both its `prescribed` and
935
- * `performed` sets; athlete-added/personal work that has no prescription is appended as its
936
- * own blocks. No `raw` is needed to see logged results.
997
+ * (`summarizedSavedWorkout.saved_workout`). Prescription blocks are enriched with logged slots;
998
+ * athlete-added / personal work with no prescription is appended as its own block.
937
999
  */
938
- function presentAthleteWorkout(raw) {
1000
+ function mergeAthleteWorkout(raw) {
939
1001
  const rec = raw;
940
1002
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
941
1003
  const workout = isRecord(ssw.workout) ? ssw.workout : {};
942
1004
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : {};
943
1005
  const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
944
1006
  const logged = savedSets(saved);
945
- const performedById = performedByExerciseId(logged);
946
- const blocks = prescriptionSets.map((s) => presentBlock(s, performedById)).sort((a, b) => a.order - b.order);
1007
+ const performedById = performedSlotsByExerciseId(logged);
1008
+ const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById)).sort((a, b) => a.order - b.order);
947
1009
  const prescribedIds = /* @__PURE__ */ new Set();
948
1010
  for (const s of prescriptionSets) {
949
1011
  const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
@@ -955,11 +1017,11 @@ function presentAthleteWorkout(raw) {
955
1017
  }
956
1018
  for (const { set, exercises } of logged) {
957
1019
  const extra = exercises.filter((ex) => {
958
- if (performedSets(ex).length === 0) return false;
1020
+ if (slotValues(ex, true).size === 0) return false;
959
1021
  const id = coerceInt(ex.workout_set_exercise_id);
960
1022
  return id === null || !prescribedIds.has(id);
961
1023
  });
962
- if (extra.length > 0) blocks.push(presentSavedBlock(set, extra));
1024
+ if (extra.length > 0) blocks.push(mergeSavedBlock(set, extra));
963
1025
  }
964
1026
  return {
965
1027
  id: coerceInt(rec.id),
@@ -968,14 +1030,126 @@ function presentAthleteWorkout(raw) {
968
1030
  program: str$1(rec.program_title),
969
1031
  team: str$1(rec.team_title),
970
1032
  instruction: str$1(workout.instruction),
971
- logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
1033
+ logged: blocks.some((b) => b.exercises.some((e) => e.sets.some((s) => s.performed !== null))),
972
1034
  personal: isPersonalSession(rec),
973
1035
  blocks
974
1036
  };
975
1037
  }
1038
+ /** The per-set displays for one side (prescribed or performed), in slot order. */
1039
+ function sideStrings(sets, pick) {
1040
+ const out = [];
1041
+ for (const s of sets) {
1042
+ const slot = pick(s);
1043
+ if (slot) out.push(fmtSlot(slot));
1044
+ }
1045
+ return out;
1046
+ }
1047
+ function toStringExercise(ex) {
1048
+ return {
1049
+ exerciseId: ex.exerciseId,
1050
+ title: ex.title,
1051
+ instruction: ex.instruction,
1052
+ units: ex.units,
1053
+ prescribed: sideStrings(ex.sets, (s) => s.prescribed),
1054
+ performed: sideStrings(ex.sets, (s) => s.performed)
1055
+ };
1056
+ }
1057
+ function toStringBlock(b) {
1058
+ return {
1059
+ order: b.order,
1060
+ title: b.title,
1061
+ instruction: b.instruction,
1062
+ isTest: b.isTest,
1063
+ exercises: b.exercises.map(toStringExercise)
1064
+ };
1065
+ }
1066
+ /**
1067
+ * Flatten one range item into a readable workout: each exercise carries its `prescribed` and
1068
+ * `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
1069
+ * prescription is appended as its own blocks. No `raw` is needed to see logged results.
1070
+ */
1071
+ function presentAthleteWorkout(raw) {
1072
+ const w = mergeAthleteWorkout(raw);
1073
+ return {
1074
+ id: w.id,
1075
+ date: w.date,
1076
+ title: w.title,
1077
+ program: w.program,
1078
+ team: w.team,
1079
+ instruction: w.instruction,
1080
+ logged: w.logged,
1081
+ personal: w.personal,
1082
+ blocks: w.blocks.map(toStringBlock)
1083
+ };
1084
+ }
976
1085
  function presentAthleteWorkouts(list) {
977
1086
  return list.map(presentAthleteWorkout);
978
1087
  }
1088
+ /** Parse a raw slot cell into an export value: a number when numeric, else the trimmed string,
1089
+ * else null. */
1090
+ function paramValue(v) {
1091
+ const n = coerceNum(v);
1092
+ if (n !== null) return n;
1093
+ return nonEmpty(v) ? String(v).trim() : null;
1094
+ }
1095
+ /**
1096
+ * Build one prescribed/performed side of a set, pulling reps/weight out of the two slots by unit.
1097
+ * The range endpoint reports weight under the fixed `lb` param-type code regardless of the
1098
+ * athlete's metric preference, so `lb` is the only weight unit that flows here.
1099
+ */
1100
+ function exportSide(slot, units) {
1101
+ const params = [{
1102
+ unit: units[0] ?? null,
1103
+ value: paramValue(slot.p1)
1104
+ }, {
1105
+ unit: units[1] ?? null,
1106
+ value: paramValue(slot.p2)
1107
+ }];
1108
+ const repsParam = params.find((p) => p.unit === "reps");
1109
+ const weightParam = params.find((p) => p.unit === "lb");
1110
+ return {
1111
+ reps: repsParam?.value ?? null,
1112
+ weight: weightParam?.value ?? null,
1113
+ weightUnit: weightParam?.unit ?? null,
1114
+ params,
1115
+ display: fmtSlot(slot)
1116
+ };
1117
+ }
1118
+ function toExportExercise(ex) {
1119
+ return {
1120
+ exerciseId: ex.exerciseId,
1121
+ title: ex.title,
1122
+ units: ex.units,
1123
+ sets: ex.sets.map((s) => ({
1124
+ set: s.set,
1125
+ prescribed: s.prescribed ? exportSide(s.prescribed, ex.units) : null,
1126
+ performed: s.performed ? exportSide(s.performed, ex.units) : null
1127
+ }))
1128
+ };
1129
+ }
1130
+ /** Flatten one workout into the structured export shape (numeric sets), from the same merge as
1131
+ * {@link presentAthleteWorkout}. */
1132
+ function presentAthleteWorkoutExport(raw) {
1133
+ const w = mergeAthleteWorkout(raw);
1134
+ return {
1135
+ id: w.id,
1136
+ date: w.date,
1137
+ title: w.title,
1138
+ program: w.program,
1139
+ team: w.team,
1140
+ logged: w.logged,
1141
+ personal: w.personal,
1142
+ blocks: w.blocks.map((b) => ({
1143
+ order: b.order,
1144
+ title: b.title,
1145
+ isTest: b.isTest,
1146
+ exercises: b.exercises.map(toExportExercise)
1147
+ }))
1148
+ };
1149
+ }
1150
+ function presentAthleteWorkoutsExport(list) {
1151
+ return list.map(presentAthleteWorkoutExport);
1152
+ }
979
1153
  /**
980
1154
  * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
981
1155
  * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
@@ -1032,8 +1206,8 @@ function presentLogTargets(list) {
1032
1206
  savedWorkoutSetExerciseId: id,
1033
1207
  title: exerciseTitle(ex),
1034
1208
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1035
- prescribed: prescribedSets(ex),
1036
- performed: performedSets(ex)
1209
+ prescribed: prescribedStrings(ex),
1210
+ performed: performedStrings(ex)
1037
1211
  };
1038
1212
  }).filter((e) => e !== null);
1039
1213
  targets.push({
@@ -1052,10 +1226,11 @@ function presentLogTargets(list) {
1052
1226
  return targets;
1053
1227
  }
1054
1228
  /**
1055
- * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
1056
- * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
1057
- * completion flag). `limit` keeps the most recent N by date (newest first). Both are pure
1058
- * post-filters over the presented view; the raw API path is left untouched.
1229
+ * Narrow a workout list for the common "what did I actually do" reads. `loggedOnly` keeps only
1230
+ * workouts the athlete logged a set on (the reliable signal, not the API's completion flag).
1231
+ * `limit` keeps the most recent N by date (newest first). Both are pure post-filters; the raw API
1232
+ * path is left untouched. Generic over the presented (`AthleteWorkoutView`) and exported
1233
+ * (`WorkoutHistoryExport`) shapes, which both carry `date` and `logged`, so one rule serves both.
1059
1234
  */
1060
1235
  function selectWorkouts(list, opts = {}) {
1061
1236
  let out = opts.loggedOnly === true ? list.filter((w) => w.logged) : [...list];
@@ -1800,6 +1975,132 @@ async function logSessionForAthlete(client, args) {
1800
1975
  sets
1801
1976
  };
1802
1977
  }
1978
+ //#endregion
1979
+ //#region ../js/src/workout-export.ts
1980
+ const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
1981
+ /** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
1982
+ function workoutsToJson(workouts) {
1983
+ return JSON.stringify(workouts, null, 2);
1984
+ }
1985
+ const CSV_HEADER = [
1986
+ "date",
1987
+ "program",
1988
+ "team",
1989
+ "workout",
1990
+ "block",
1991
+ "exercise",
1992
+ "set",
1993
+ "prescribed_reps",
1994
+ "prescribed_weight",
1995
+ "performed_reps",
1996
+ "performed_weight",
1997
+ "weight_unit",
1998
+ "prescribed",
1999
+ "performed"
2000
+ ];
2001
+ /**
2002
+ * Format a CSV cell. Numbers pass through verbatim. For strings: neutralize spreadsheet formula
2003
+ * injection first — a text cell that opens with `=`, `+`, `-`, `@`, tab, or CR is prefixed with a
2004
+ * single quote so Excel/Sheets treat a coach-authored title like `=HYPERLINK(...)` as text, not a
2005
+ * formula — then quote (and double internal quotes) when the value holds a comma, quote, or newline.
2006
+ */
2007
+ function csvCell(value) {
2008
+ if (value === null || value === void 0) return "";
2009
+ if (typeof value === "number") return String(value);
2010
+ const guarded = /^[=+\-@\t\r]/u.test(value) ? `'${value}` : value;
2011
+ return /["\n\r,]/u.test(guarded) ? `"${guarded.replace(/"/gu, "\"\"")}"` : guarded;
2012
+ }
2013
+ /**
2014
+ * One row per set. `reps`/`weight` columns hold the broken-out numeric values for the common
2015
+ * lifting case; the trailing `prescribed`/`performed` columns hold the raw `"p1 @ p2"` display so a
2016
+ * time, distance, or percentage exercise (where the reps/weight columns are blank) loses nothing.
2017
+ */
2018
+ function workoutsToCsv(workouts) {
2019
+ const rows = [CSV_HEADER.join(",")];
2020
+ for (const w of workouts) for (const block of w.blocks) for (const ex of block.exercises) for (const set of ex.sets) {
2021
+ const p = set.prescribed;
2022
+ const q = set.performed;
2023
+ rows.push([
2024
+ w.date,
2025
+ w.program,
2026
+ w.team,
2027
+ w.title,
2028
+ block.title,
2029
+ ex.title,
2030
+ set.set,
2031
+ p?.reps,
2032
+ p?.weight,
2033
+ q?.reps,
2034
+ q?.weight,
2035
+ q?.weightUnit ?? p?.weightUnit,
2036
+ p?.display,
2037
+ q?.display
2038
+ ].map(csvCell).join(","));
2039
+ }
2040
+ return `${rows.join("\r\n")}\r\n`;
2041
+ }
2042
+ /** The set of unit labels an exercise uses, e.g. `"reps, lb"`. */
2043
+ function unitsLabel(units) {
2044
+ const named = units.filter((u) => u !== null);
2045
+ return named.length > 0 ? ` (${named.join(", ")})` : "";
2046
+ }
2047
+ function sideText(side) {
2048
+ return side && side.display !== "" ? side.display : "—";
2049
+ }
2050
+ /** A readable, indented rendering — one athlete-friendly block of text per session. */
2051
+ function workoutsToText(workouts) {
2052
+ const lines = [
2053
+ "# TrainHeroic workout history",
2054
+ `# ${`${workouts.length} session${workouts.length === 1 ? "" : "s"}`}`,
2055
+ ""
2056
+ ];
2057
+ for (const w of workouts) {
2058
+ lines.push(`${w.date} ${w.title || "(untitled)"}`);
2059
+ const scope = [w.program && `Program: ${w.program}`, w.team && `Team: ${w.team}`].filter(Boolean);
2060
+ if (scope.length > 0) lines.push(scope.join(" · "));
2061
+ if (w.personal) lines.push("(personal session)");
2062
+ for (const block of w.blocks) {
2063
+ if (block.exercises.length === 0) continue;
2064
+ if (block.title) lines.push(` ${block.title}`);
2065
+ for (const ex of block.exercises) {
2066
+ lines.push(` ${ex.title || "(exercise)"}${unitsLabel(ex.units)}`);
2067
+ for (const set of ex.sets) {
2068
+ const done = sideText(set.performed);
2069
+ const planned = set.prescribed ? ` (planned ${sideText(set.prescribed)})` : "";
2070
+ lines.push(` set ${set.set} ${done}${planned}`);
2071
+ }
2072
+ }
2073
+ }
2074
+ lines.push("");
2075
+ }
2076
+ return lines.join("\n");
2077
+ }
2078
+ const FORMAT_META = {
2079
+ json: {
2080
+ contentType: "application/json",
2081
+ extension: "json"
2082
+ },
2083
+ csv: {
2084
+ contentType: "text/csv",
2085
+ extension: "csv"
2086
+ },
2087
+ text: {
2088
+ contentType: "text/plain",
2089
+ extension: "txt"
2090
+ }
2091
+ };
2092
+ /** Serialize the workout history to the chosen format, with content-type and a suggested filename. */
2093
+ function serializeWorkoutHistory(workouts, format, opts = {}) {
2094
+ const meta = FORMAT_META[format];
2095
+ const content = format === "json" ? workoutsToJson(workouts) : format === "csv" ? workoutsToCsv(workouts) : workoutsToText(workouts);
2096
+ const base = opts.filenameBase ?? DEFAULT_FILENAME_BASE;
2097
+ return {
2098
+ content,
2099
+ contentType: meta.contentType,
2100
+ extension: meta.extension,
2101
+ filename: `${base}.${meta.extension}`
2102
+ };
2103
+ }
1803
2104
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1804
2105
  function emailList(emails) {
1805
2106
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2823,7 +3124,7 @@ var ExerciseLibrary = class {
2823
3124
  await this.ensureFresh();
2824
3125
  const s = this.#byId.get(id);
2825
3126
  if (!s) return null;
2826
- return presentExercise$1(s.raw);
3127
+ return presentExercise(s.raw);
2827
3128
  }
2828
3129
  async defaults(id) {
2829
3130
  const s = this.#byId.get(id);
@@ -3058,7 +3359,7 @@ Coach — manage a roster (needs a coach account):
3058
3359
 
3059
3360
  Athlete — the logged-in user's own training (a coach account works too):
3060
3361
  athlete whoami | profile [--metric] | prefs | working-maxes
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')
3362
+ athlete workouts --start Y-M-D --end Y-M-D [--raw] [--logged-only] [--limit N] [--summary] [--format json|csv|text] (reads what you did; --format exports history with reps/weight broken out; for the log ids use 'athlete log-targets')
3062
3363
  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)
3063
3364
  athlete exercises [--q <text>] [--limit N]
3064
3365
  athlete history <exerciseId> [--raw]
@@ -3069,11 +3370,24 @@ Athlete — the logged-in user's own training (a coach account works too):
3069
3370
  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)
3070
3371
  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
3372
  athlete session-remove --id <programWorkoutId> --date Y-M-D --yes (delete a stray PERSONAL session; the id is the session 'id' from 'athlete workouts')
3373
+ athlete swap-exercise --set-exercise <savedWorkoutSetExerciseId> --exercise <exerciseId> --yes (substitute one prescribed exercise in a COACH-SCHEDULED slot for a different one — your copy only; slot id from 'athlete log-targets', exerciseId from 'athlete exercises')
3072
3374
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
3073
3375
  `;
3074
3376
  function out(value) {
3075
3377
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
3076
3378
  }
3379
+ function outRaw(text) {
3380
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
3381
+ }
3382
+ const EXPORT_FORMATS = [
3383
+ "json",
3384
+ "csv",
3385
+ "text"
3386
+ ];
3387
+ function asExportFormat(value) {
3388
+ if (EXPORT_FORMATS.includes(value)) return value;
3389
+ return fail(`--format must be one of ${EXPORT_FORMATS.join(", ")}, got "${value}".`);
3390
+ }
3077
3391
  function fail(message) {
3078
3392
  process.stderr.write(`error: ${message}\n`);
3079
3393
  process.exit(1);
@@ -3343,7 +3657,7 @@ async function cmdAthleteExport(client, a) {
3343
3657
  fetchAthleteProfileSummary(client, userId),
3344
3658
  fetchAthleteUser(client, userId),
3345
3659
  fetchAthletePrefs(client),
3346
- fetchAthleteWorkouts(client, start, end),
3660
+ fetchAthleteWorkoutsChunked(client, start, end),
3347
3661
  fetchExerciseHistoryList(client),
3348
3662
  fetchWorkingMaxes(client)
3349
3663
  ]);
@@ -3484,6 +3798,54 @@ async function cmdAthleteSessionRemove(client, a) {
3484
3798
  date: args.date
3485
3799
  });
3486
3800
  }
3801
+ const ATHLETE_SWAP_EXERCISE_USAGE = "athlete swap-exercise --set-exercise <savedWorkoutSetExerciseId> --exercise <exerciseId> --yes";
3802
+ async function cmdAthleteSwapExercise(client, a) {
3803
+ const { values } = parse(a, {
3804
+ "set-exercise": { type: "string" },
3805
+ exercise: { type: "string" },
3806
+ yes: { type: "boolean" }
3807
+ });
3808
+ const savedWorkoutSetExerciseId = toInt(need(values["set-exercise"], ATHLETE_SWAP_EXERCISE_USAGE), "--set-exercise");
3809
+ const exerciseId = toInt(need(values.exercise, ATHLETE_SWAP_EXERCISE_USAGE), "--exercise");
3810
+ validate(swapAthleteExerciseArgsSchema, {
3811
+ savedWorkoutSetExerciseId,
3812
+ exerciseId
3813
+ }, "athlete swap-exercise args");
3814
+ if (values.yes !== true) fail(`swapping slot ${savedWorkoutSetExerciseId} changes what that slot is prescribed; add --yes.`);
3815
+ return out(await swapAthleteExercise(client, {
3816
+ savedWorkoutSetExerciseId,
3817
+ exerciseId
3818
+ }));
3819
+ }
3820
+ async function cmdAthleteWorkouts(client, a) {
3821
+ const { values } = parse(a, {
3822
+ start: { type: "string" },
3823
+ end: { type: "string" },
3824
+ raw: { type: "boolean" },
3825
+ "log-ids": { type: "boolean" },
3826
+ "logged-only": { type: "boolean" },
3827
+ limit: { type: "string" },
3828
+ summary: { type: "boolean" },
3829
+ format: { type: "string" }
3830
+ });
3831
+ const start = isoDate(need(values.start, "athlete workouts --start Y-M-D --end Y-M-D"), "--start");
3832
+ const end = isoDate(need(values.end, "athlete workouts --start Y-M-D --end Y-M-D"), "--end");
3833
+ const format = values.format !== void 0 ? asExportFormat(values.format) : void 0;
3834
+ if (format !== void 0 && (values.raw === true || values["log-ids"] === true || values.summary === true)) fail("--format cannot be combined with --raw, --log-ids, or --summary.");
3835
+ const opts = {};
3836
+ if (values["logged-only"] === true) opts.loggedOnly = true;
3837
+ if (values.limit !== void 0) {
3838
+ const limit = toInt(values.limit, "--limit");
3839
+ if (!Number.isInteger(limit) || limit < 0) fail(`--limit must be a non-negative integer.`);
3840
+ opts.limit = limit;
3841
+ }
3842
+ const workouts = await fetchAthleteWorkoutsChunked(client, start, end);
3843
+ if (format !== void 0) return outRaw(serializeWorkoutHistory(selectWorkouts(presentAthleteWorkoutsExport(workouts), opts), format).content);
3844
+ if (values["log-ids"] === true) return out(presentLogTargets(workouts));
3845
+ if (values.raw === true) return out(workouts);
3846
+ const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
3847
+ return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
3848
+ }
3487
3849
  async function cmdAthlete(client, rest) {
3488
3850
  const [sub, ...a] = rest;
3489
3851
  switch (sub) {
@@ -3498,25 +3860,7 @@ async function cmdAthlete(client, rest) {
3498
3860
  });
3499
3861
  }
3500
3862
  case "prefs": return out(await fetchAthletePrefs(client));
3501
- case "workouts": {
3502
- const { values } = parse(a, {
3503
- start: { type: "string" },
3504
- end: { type: "string" },
3505
- raw: { type: "boolean" },
3506
- "log-ids": { type: "boolean" },
3507
- "logged-only": { type: "boolean" },
3508
- limit: { type: "string" },
3509
- summary: { type: "boolean" }
3510
- });
3511
- const workouts = await fetchAthleteWorkouts(client, isoDate(need(values.start, "athlete workouts --start Y-M-D --end Y-M-D"), "--start"), isoDate(need(values.end, "athlete workouts --start Y-M-D --end Y-M-D"), "--end"));
3512
- if (values["log-ids"] === true) return out(presentLogTargets(workouts));
3513
- if (values.raw === true) return out(workouts);
3514
- const opts = {};
3515
- if (values["logged-only"] === true) opts.loggedOnly = true;
3516
- if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
3517
- const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
3518
- return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
3519
- }
3863
+ case "workouts": return cmdAthleteWorkouts(client, a);
3520
3864
  case "exercises": {
3521
3865
  const { values } = parse(a, {
3522
3866
  q: { type: "string" },
@@ -3557,7 +3901,8 @@ async function cmdAthlete(client, rest) {
3557
3901
  case "log-set": return cmdAthleteLogSet(client, a);
3558
3902
  case "log-session": return cmdAthleteLogSession(client, a);
3559
3903
  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>");
3904
+ case "swap-exercise": return cmdAthleteSwapExercise(client, a);
3905
+ 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|swap-exercise>");
3561
3906
  }
3562
3907
  }
3563
3908
  async function cmdSkill(rest) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
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.6.1",
25
- "@trainheroic-unofficial/js": "1.6.1"
24
+ "@trainheroic-unofficial/dto": "1.7.1",
25
+ "@trainheroic-unofficial/js": "1.7.1"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.1",
@@ -52,21 +52,22 @@ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`.
52
52
 
53
53
  ## What you can do
54
54
 
55
- | Goal | Command |
56
- | ------------------------------------- | ------------------------------------------------------------------------------ |
57
- | Lifetime totals + profile | `$TH athlete profile [--metric]` |
58
- | Scheduled / completed workouts | `$TH athlete workouts --start Y-M-D --end Y-M-D [--raw] [--summary]` |
59
- | Find an exercise you've logged | `$TH athlete exercises [--q <text>] [--limit N]` |
60
- | One lift's PRs + history over time | `$TH athlete history <exerciseId> [--raw]` |
61
- | Personal records for a lift | `$TH athlete prs <exerciseId>` |
62
- | Last performance + PR as of a date | `$TH athlete stats <exerciseId> --date Y-M-D` |
63
- | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
- | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
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>]` |
67
- | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
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` |
55
+ | Goal | Command |
56
+ | ------------------------------------- | -------------------------------------------------------------------------------- |
57
+ | Lifetime totals + profile | `$TH athlete profile [--metric]` |
58
+ | Scheduled / completed workouts | `$TH athlete workouts --start Y-M-D --end Y-M-D [--raw] [--summary]` |
59
+ | Find an exercise you've logged | `$TH athlete exercises [--q <text>] [--limit N]` |
60
+ | One lift's PRs + history over time | `$TH athlete history <exerciseId> [--raw]` |
61
+ | Personal records for a lift | `$TH athlete prs <exerciseId>` |
62
+ | Last performance + PR as of a date | `$TH athlete stats <exerciseId> --date Y-M-D` |
63
+ | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
+ | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
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>]` |
67
+ | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
68
+ | Log an off-plan session (gated) | `$TH athlete log-session --date Y-M-D '[{"exerciseId":N,"sets":[...]}]' --yes` |
69
+ | Swap a prescribed exercise (gated) | `$TH athlete swap-exercise --set-exercise <sweId> --exercise <exerciseId> --yes` |
70
+ | Remove a stray personal session | `$TH athlete session-remove --id <programWorkoutId> --date Y-M-D --yes` |
70
71
 
71
72
  ## Reading training
72
73
 
@@ -145,6 +146,24 @@ $TH athlete log-session --date 2026-06-21 --yes \
145
146
  Same coach-visible write and the same `--yes` gate as `log-set`. For a workout the coach
146
147
  already scheduled, prefer `log-set` so it attaches to the prescription.
147
148
 
149
+ ### Swapping a prescribed exercise
150
+
151
+ To substitute one movement in a coach-scheduled workout for a different one (the in-app "swap
152
+ exercise"), use `swap-exercise`. It changes which exercise the slot is, for your copy only —
153
+ the team/program prescription stays as the coach set it. Get the slot's
154
+ `savedWorkoutSetExerciseId` from `$TH athlete log-targets` (each row lists it per exercise) and
155
+ the replacement `exerciseId` from `$TH athlete exercises`, then swap:
156
+
157
+ ```bash
158
+ $TH athlete log-targets --start 2026-06-01 --end 2026-06-01 --program "Bodybuilding"
159
+ $TH athlete swap-exercise --set-exercise 1599201 --exercise 920003 --yes
160
+ ```
161
+
162
+ Do this **before** logging: `log-set` records results into a slot without changing its
163
+ exercise, so swap first, then log against the new movement as usual. Same `--yes` gate; re-read
164
+ the workout with `$TH athlete workouts --start Y-M-D --end Y-M-D` to confirm the slot now shows
165
+ the replacement.
166
+
148
167
  ## Gotchas
149
168
 
150
169
  - `profile` must send `use_metric` and `stats` must send `date`, or the API returns 400.