@trainheroic-unofficial/cli 1.4.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 +162 -65
  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
@@ -583,6 +605,10 @@ function asExerciseList(body) {
583
605
  function isRecord(x) {
584
606
  return typeof x === "object" && x !== null && !Array.isArray(x);
585
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
+ }
586
612
  /**
587
613
  * Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
588
614
  * exact title, then prefix, then count of matched tokens, with shorter titles and
@@ -762,7 +788,6 @@ function fetchLeaderboard(client, workoutId, opts = {}) {
762
788
  const query = qs.toString();
763
789
  return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
764
790
  }
765
- const SLOTS = 10;
766
791
  function nonEmpty(value) {
767
792
  return value !== void 0 && value !== null && String(value).trim() !== "";
768
793
  }
@@ -773,7 +798,7 @@ function nonEmpty(value) {
773
798
  */
774
799
  function prescribedSets(ex) {
775
800
  const out = [];
776
- for (let i = 1; i <= SLOTS; i += 1) {
801
+ for (let i = 1; i <= 10; i += 1) {
777
802
  const p1 = ex[`param_1_data_${i}`];
778
803
  const p2 = ex[`param_2_data_${i}`];
779
804
  const has1 = nonEmpty(p1);
@@ -794,7 +819,7 @@ function prescribedSets(ex) {
794
819
  */
795
820
  function performedSets(ex) {
796
821
  const out = [];
797
- for (let i = 1; i <= SLOTS; i += 1) {
822
+ for (let i = 1; i <= 10; i += 1) {
798
823
  if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
799
824
  const p1 = ex[`param_1_data_${i}`];
800
825
  const p2 = ex[`param_2_data_${i}`];
@@ -828,9 +853,6 @@ function presentBlock(set, performedById) {
828
853
  exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
829
854
  };
830
855
  }
831
- function str$1(v) {
832
- return typeof v === "string" && v !== "" ? v : null;
833
- }
834
856
  /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
835
857
  function savedSets(saved) {
836
858
  const out = [];
@@ -1083,7 +1105,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1083
1105
  sessions
1084
1106
  };
1085
1107
  }
1086
- 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
1087
1131
  /**
1088
1132
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1089
1133
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1098,10 +1142,11 @@ function toSetResults(results) {
1098
1142
  return {
1099
1143
  savedWorkoutSetExerciseId: id,
1100
1144
  sets: r.sets.map((s) => {
1101
- const slot = {};
1102
- if (s.param1 !== void 0) slot.param1 = s.param1;
1103
- if (s.param2 !== void 0) slot.param2 = s.param2;
1104
- 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;
1105
1150
  })
1106
1151
  };
1107
1152
  });
@@ -1113,36 +1158,96 @@ function toSetResults(results) {
1113
1158
  *
1114
1159
  * `mode` selects which write this is — the same endpoint serves both:
1115
1160
  * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1116
- * 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.
1117
1162
  * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1118
1163
  * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1119
1164
  * coach edits an athlete's prescribed reps/weight.
1120
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
+ *
1121
1175
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1122
- * 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`.
1123
1178
  *
1124
1179
  * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1125
1180
  */
1126
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1127
- 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
+ });
1128
1190
  const performed = mode === "log";
1129
- const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1191
+ const carryOver = performed && existing !== void 0;
1130
1192
  const body = {
1131
1193
  id: savedWorkoutSetExerciseId,
1132
1194
  saved_workout_set_id: savedWorkoutSetId,
1133
- workout_set_exercise_id: workoutSetExerciseId,
1134
- completed: performed && hasData ? 1 : 0
1195
+ workout_set_exercise_id: workoutSetExerciseId
1135
1196
  };
1136
- for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1137
- const slot = results[i - 1];
1138
- const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1139
- const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1140
- 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;
1141
1218
  body[`param_1_data_${i}`] = p1;
1142
1219
  body[`param_2_data_${i}`] = p2;
1143
1220
  }
1221
+ body.completed = performed && anyMade ? 1 : 0;
1144
1222
  return body;
1145
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
+ }
1146
1251
  /**
1147
1252
  * Locate the target saved workout set across all program workouts on the given day.
1148
1253
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1241,7 +1346,8 @@ async function logAthleteSet(client, args) {
1241
1346
  const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1242
1347
  return {
1243
1348
  savedWorkoutSetId: r.savedWorkoutSetId,
1244
- exercisesLogged: r.exercisesWritten
1349
+ exercisesLogged: r.exercisesWritten,
1350
+ setCompleted: r.setCompleted
1245
1351
  };
1246
1352
  }
1247
1353
  /**
@@ -1262,7 +1368,8 @@ async function logForAthlete(client, args) {
1262
1368
  }, workouts, args.savedWorkoutSetId, args.results, "log");
1263
1369
  return {
1264
1370
  savedWorkoutSetId: r.savedWorkoutSetId,
1265
- exercisesLogged: r.exercisesWritten
1371
+ exercisesLogged: r.exercisesWritten,
1372
+ setCompleted: r.setCompleted
1266
1373
  };
1267
1374
  }
1268
1375
  /**
@@ -1357,7 +1464,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1357
1464
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1358
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.`);
1359
1466
  const body = {
1360
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1467
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1361
1468
  ...extra
1362
1469
  };
1363
1470
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
@@ -1367,17 +1474,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1367
1474
  }
1368
1475
  exercisesWritten += 1;
1369
1476
  }
1477
+ let setCompleted = false;
1370
1478
  if (mode === "log") {
1371
- const setBody = {
1372
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1373
- ...extra
1374
- };
1375
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1376
- 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
+ }
1377
1488
  }
1378
1489
  return {
1379
1490
  savedWorkoutSetId,
1380
- exercisesWritten
1491
+ exercisesWritten,
1492
+ setCompleted
1381
1493
  };
1382
1494
  }
1383
1495
  /**
@@ -1534,7 +1646,10 @@ async function logResolvedExercises(client, target, date, resolved) {
1534
1646
  savedWorkoutSetId,
1535
1647
  results
1536
1648
  });
1537
- out.push(written);
1649
+ out.push({
1650
+ savedWorkoutSetId: written.savedWorkoutSetId,
1651
+ exercisesLogged: written.exercisesLogged
1652
+ });
1538
1653
  }
1539
1654
  return out;
1540
1655
  }
@@ -1612,27 +1727,6 @@ async function logSessionForAthlete(client, args) {
1612
1727
  sets
1613
1728
  };
1614
1729
  }
1615
- /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1616
- function presentExerciseHistory(detail) {
1617
- return {
1618
- liftPRs: (detail.liftPRs ?? []).map((p) => ({
1619
- description: p.description ?? null,
1620
- reps: p.reps ?? null,
1621
- weight: p.weight ?? null,
1622
- units: p.units ?? null,
1623
- date: p.dateCompleted ?? null
1624
- })),
1625
- sessions: (detail.history ?? []).map((h) => ({
1626
- date: h.dateCompleted,
1627
- abr: h.abr ?? null,
1628
- estimated1RM: h.bestEstimated1RM ?? null,
1629
- sets: (h.sets ?? []).map((s) => ({
1630
- setNumber: s.setNumber,
1631
- value: s.formattedValue ?? null
1632
- }))
1633
- }))
1634
- };
1635
- }
1636
1730
  /** Normalize one-or-many emails into a deduped, trimmed list. */
1637
1731
  function emailList(emails) {
1638
1732
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2823,6 +2917,9 @@ Coach — manage a roster (needs a coach account):
2823
2917
  --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2824
2918
  and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2825
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.
2826
2923
  coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2827
2924
  log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2828
2925
  already on the athlete's calendar that day. The API can't put an off-plan session on an
@@ -2895,7 +2992,7 @@ Athlete — the logged-in user's own training (a coach account works too):
2895
2992
  athlete stats <exerciseId> --date Y-M-D
2896
2993
  athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2897
2994
  athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2898
- 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)
2899
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')
2900
2997
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2901
2998
  `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.4.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.4.0",
25
- "@trainheroic-unofficial/js": "1.4.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",