@trainheroic-unofficial/cli 3.5.0 → 3.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.mjs +481 -136
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -718,6 +718,12 @@ const exerciseSpecSchema = z.object({
718
718
  instr: z.string().optional(),
719
719
  param_1_type: z.number().optional(),
720
720
  param_2_type: z.number().optional()
721
+ }).superRefine((exercise, ctx) => {
722
+ if (Array.isArray(exercise.reps) && Array.isArray(exercise.weight) && exercise.reps.length !== exercise.weight.length) ctx.addIssue({
723
+ code: "custom",
724
+ message: `Per-set reps and weight arrays must have the same length; received ${exercise.reps.length} reps and ${exercise.weight.length} weights.`,
725
+ path: ["weight"]
726
+ });
721
727
  });
722
728
  /** A block's Red-Zone leaderboard: a unit string/number, or an object with options. */
723
729
  const leaderboardSpecSchema = z.union([
@@ -757,15 +763,19 @@ const workoutSpecSchema = z.object({
757
763
  /**
758
764
  * Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
759
765
  * conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
760
- * as a valid date. Each part must be an integer.
766
+ * as a valid date. Each part must be a run of digits (`Number("")` is 0, so a blank part such as
767
+ * the trailing one in "2026-9-" must be rejected explicitly), and month/day must be in range so
768
+ * a typo cannot land a session on a date the calendar does not have.
761
769
  */
762
770
  function parseWorkoutDate(s) {
763
- const parts = s.split("-").map((p) => Number(p));
764
- if (parts.length !== 3 || parts.some((n) => !Number.isInteger(n))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
771
+ const parts = s.split("-");
772
+ if (parts.length !== 3 || parts.some((p) => !/^\d+$/u.test(p))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
773
+ const [year, month, day] = parts.map(Number);
774
+ if (month < 1 || month > 12 || day < 1 || day > 31) throw new Error(`date must be YYYY-M-D with a real month and day, got "${s}".`);
765
775
  return [
766
- parts[0],
767
- parts[1],
768
- parts[2]
776
+ year,
777
+ month,
778
+ day
769
779
  ];
770
780
  }
771
781
  /** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
@@ -968,6 +978,26 @@ function checkResponse(schema, data, label) {
968
978
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
969
979
  }
970
980
  //#endregion
981
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
982
+ /**
983
+ * Creates a duplicate-free version of an array.
984
+ *
985
+ * This function takes an array and returns a new array containing only the unique values
986
+ * from the original array, preserving the order of first occurrence.
987
+ *
988
+ * @template T - The type of elements in the array.
989
+ * @param arr - The array to process.
990
+ * @returns A new array with only unique values from the original array.
991
+ *
992
+ * @example
993
+ * const array = [1, 2, 2, 3, 4, 4, 5];
994
+ * const result = uniq(array);
995
+ * // result will be [1, 2, 3, 4, 5]
996
+ */
997
+ function uniq(arr) {
998
+ return [...new Set(arr)];
999
+ }
1000
+ //#endregion
971
1001
  //#region ../js/src/exercise-util.ts
972
1002
  /**
973
1003
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -1141,18 +1171,76 @@ function rankSearch(rows, query, limit) {
1141
1171
  * on workerd, blowing the subrequest budget.
1142
1172
  */
1143
1173
  async function mapPool(items, limit, fn) {
1174
+ assertPositiveInteger(limit, "Concurrency limit");
1144
1175
  const out = Array.from({ length: items.length });
1145
1176
  let next = 0;
1177
+ const state = { failure: null };
1146
1178
  const worker = async () => {
1147
- while (next < items.length) {
1179
+ while (next < items.length && state.failure === null) {
1148
1180
  const i = next;
1149
1181
  next += 1;
1150
- out[i] = await fn(items[i], i);
1182
+ try {
1183
+ out[i] = await fn(items[i], i);
1184
+ } catch (error) {
1185
+ state.failure ??= { error };
1186
+ }
1151
1187
  }
1152
1188
  };
1153
1189
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
1190
+ if (state.failure !== null) throw state.failure.error;
1154
1191
  return out;
1155
1192
  }
1193
+ function createLimiter(max) {
1194
+ assertPositiveInteger(max, "Maximum concurrency");
1195
+ let active = 0;
1196
+ let cancelled = null;
1197
+ const waiting = [];
1198
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
1199
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
1200
+ else if (active < max) {
1201
+ active += 1;
1202
+ resolve();
1203
+ } else waiting.push({
1204
+ start: () => {
1205
+ active += 1;
1206
+ resolve();
1207
+ },
1208
+ abort: reject,
1209
+ finalizer
1210
+ });
1211
+ });
1212
+ const release = () => {
1213
+ active -= 1;
1214
+ waiting.shift()?.start();
1215
+ };
1216
+ return {
1217
+ async run(task) {
1218
+ await acquire(false);
1219
+ try {
1220
+ return await task();
1221
+ } finally {
1222
+ release();
1223
+ }
1224
+ },
1225
+ async runFinalizer(task) {
1226
+ await acquire(true);
1227
+ try {
1228
+ return await task();
1229
+ } finally {
1230
+ release();
1231
+ }
1232
+ },
1233
+ cancel(error) {
1234
+ cancelled ??= { error };
1235
+ const queued = waiting.splice(0);
1236
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
1237
+ else entry.abort(error);
1238
+ }
1239
+ };
1240
+ }
1241
+ function assertPositiveInteger(value, label) {
1242
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1243
+ }
1156
1244
  //#endregion
1157
1245
  //#region ../js/src/athlete.ts
1158
1246
  async function getJson(client, path, label) {
@@ -1206,39 +1294,25 @@ function sortRosterByRecency(rows) {
1206
1294
  * summary becomes a null-data row (sorted last), not an error.
1207
1295
  */
1208
1296
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1209
- const rows = [];
1210
- const concurrency = 6;
1211
- const uniqueAthleteIds = [...new Set(athleteIds)];
1212
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
1213
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
1214
- const settled = await Promise.all(chunk.map(async (id) => {
1215
- try {
1216
- return {
1217
- id,
1218
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
1219
- };
1220
- } catch {
1221
- return {
1222
- id,
1223
- summary: null
1224
- };
1225
- }
1226
- }));
1227
- for (const { id, summary } of settled) {
1228
- const count = summary?.sessions_count ?? null;
1229
- const hasSessions = count !== null && count > 0;
1230
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1231
- rows.push({
1232
- athleteId: id,
1233
- sessionsCount: count,
1234
- firstLoggedDate: normDate(summary?.first_logged_date),
1235
- lastLoggedDate: normDate(summary?.last_logged_date),
1236
- totalReps: summary?.reps_sum ?? null,
1237
- totalVolume: summary?.volume_sum ?? null
1238
- });
1297
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
1298
+ let summary;
1299
+ try {
1300
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
1301
+ } catch {
1302
+ summary = null;
1239
1303
  }
1240
- }
1241
- return sortRosterByRecency(rows);
1304
+ const count = summary?.sessions_count ?? null;
1305
+ const hasSessions = count !== null && count > 0;
1306
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1307
+ return {
1308
+ athleteId: id,
1309
+ sessionsCount: count,
1310
+ firstLoggedDate: normDate(summary?.first_logged_date),
1311
+ lastLoggedDate: normDate(summary?.last_logged_date),
1312
+ totalReps: summary?.reps_sum ?? null,
1313
+ totalVolume: summary?.volume_sum ?? null
1314
+ };
1315
+ }));
1242
1316
  }
1243
1317
  function fetchAthletePrefs(client) {
1244
1318
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
@@ -1258,9 +1332,19 @@ function fetchAthleteCircuits(client, kind = "recent") {
1258
1332
  function fetchAthleteProgrammingPrograms(client) {
1259
1333
  return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
1260
1334
  }
1261
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
1335
+ /**
1336
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
1337
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
1338
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
1339
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
1340
+ */
1262
1341
  async function searchExerciseHistory(client, query, limit = 20) {
1263
- return rankSearch(await fetchExerciseHistoryList(client), query, limit);
1342
+ const tokens = buildSearchText(query).split(/\s+/u).filter((t) => t.length > 0);
1343
+ if (tokens.length === 0) return [];
1344
+ return rankSearch((await fetchExerciseHistoryList(client)).filter((row) => {
1345
+ const text = buildSearchText(row.title);
1346
+ return tokens.every((t) => text.includes(t));
1347
+ }), query, limit);
1264
1348
  }
1265
1349
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1266
1350
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -1375,6 +1459,28 @@ function slotValues(ex, requireMade) {
1375
1459
  }
1376
1460
  return map;
1377
1461
  }
1462
+ /**
1463
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
1464
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
1465
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
1466
+ * only prescription, since personal work has no template tree at all.
1467
+ */
1468
+ function unmadeSlotValues(ex) {
1469
+ const map = slotValues(ex, false);
1470
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
1471
+ return map;
1472
+ }
1473
+ /**
1474
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
1475
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
1476
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
1477
+ * slots are the whole prescription.
1478
+ */
1479
+ function prescriptionSlots(template, saved) {
1480
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
1481
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
1482
+ return map;
1483
+ }
1378
1484
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
1379
1485
  function fmtSlot(slot) {
1380
1486
  const has1 = slot.p1 !== null;
@@ -1384,10 +1490,6 @@ function fmtSlot(slot) {
1384
1490
  if (has2) return `@ ${slot.p2}`;
1385
1491
  return "";
1386
1492
  }
1387
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
1388
- function prescribedStrings(ex) {
1389
- return [...slotValues(ex, false).values()].map(fmtSlot);
1390
- }
1391
1493
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
1392
1494
  function performedStrings(ex) {
1393
1495
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -1409,6 +1511,46 @@ function savedSets(saved) {
1409
1511
  return out;
1410
1512
  }
1411
1513
  /**
1514
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
1515
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
1516
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
1517
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
1518
+ */
1519
+ function performedExercises(workouts) {
1520
+ const out = [];
1521
+ for (const pw of workouts) {
1522
+ const rec = pw;
1523
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1524
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1525
+ const templates = /* @__PURE__ */ new Map();
1526
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1527
+ if (!isRecord(set)) continue;
1528
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1529
+ for (const ex of exercises) {
1530
+ if (!isRecord(ex)) continue;
1531
+ const id = coerceInt(ex.id);
1532
+ if (id !== null) templates.set(id, {
1533
+ exerciseId: coerceInt(ex.exercise_id),
1534
+ title: exerciseTitle(ex)
1535
+ });
1536
+ }
1537
+ }
1538
+ const saved = savedWorkoutOf(pw);
1539
+ if (!saved) continue;
1540
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
1541
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1542
+ const template = templateId === null ? void 0 : templates.get(templateId);
1543
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
1544
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
1545
+ out.push({
1546
+ exerciseId,
1547
+ title: exerciseTitle(ex, template?.title)
1548
+ });
1549
+ }
1550
+ }
1551
+ return out;
1552
+ }
1553
+ /**
1412
1554
  * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
1413
1555
  * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
1414
1556
  * entered values live in the same `param_N_data` slots as a prescription.
@@ -1423,6 +1565,15 @@ function performedSlotsByExerciseId(sets) {
1423
1565
  }
1424
1566
  return map;
1425
1567
  }
1568
+ /** Each saved-copy row keyed by the prescription exercise id it was copied from. */
1569
+ function savedRowsByTemplateId(sets) {
1570
+ const map = /* @__PURE__ */ new Map();
1571
+ for (const { exercises } of sets) for (const ex of exercises) {
1572
+ const id = coerceInt(ex.workout_set_exercise_id);
1573
+ if (id !== null && !map.has(id)) map.set(id, ex);
1574
+ }
1575
+ return map;
1576
+ }
1426
1577
  /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
1427
1578
  function notesByTemplateId(sets) {
1428
1579
  const map = /* @__PURE__ */ new Map();
@@ -1446,7 +1597,7 @@ function mergeExercise(prescribed, performed, meta) {
1446
1597
  };
1447
1598
  }
1448
1599
  /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
1449
- function mergePrescriptionBlock(set, performedById, notesById) {
1600
+ function mergePrescriptionBlock(set, performedById, savedById, notesById) {
1450
1601
  const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1451
1602
  return {
1452
1603
  order: coerceInt(set.order) ?? 0,
@@ -1456,7 +1607,7 @@ function mergePrescriptionBlock(set, performedById, notesById) {
1456
1607
  exercises: exercises.filter(isRecord).map((ex) => {
1457
1608
  const id = coerceInt(ex.id);
1458
1609
  const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
1459
- return mergeExercise(slotValues(ex, false), performed, {
1610
+ return mergeExercise(prescriptionSlots(ex, id !== null ? savedById.get(id) : void 0), performed, {
1460
1611
  exerciseId: coerceInt(ex.exercise_id),
1461
1612
  title: typeof ex.title === "string" ? ex.title : "",
1462
1613
  instruction: str$1(ex.instruction),
@@ -1466,14 +1617,18 @@ function mergePrescriptionBlock(set, performedById, notesById) {
1466
1617
  })
1467
1618
  };
1468
1619
  }
1469
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
1620
+ /**
1621
+ * A block straight from the saved copy (athlete-added or personal work; no template row). Its
1622
+ * unperformed slots are the prescription — a personal session's targets live only here — and its
1623
+ * performed slots are what was logged.
1624
+ */
1470
1625
  function mergeSavedBlock(set, exercises) {
1471
1626
  return {
1472
1627
  order: coerceInt(set.order) ?? 0,
1473
1628
  title: str$1(set.title),
1474
1629
  instruction: str$1(set.instruction),
1475
1630
  isTest: coerceInt(set.is_test) === 1,
1476
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
1631
+ exercises: exercises.map((ex) => mergeExercise(prescriptionSlots(void 0, ex), slotValues(ex, true), {
1477
1632
  exerciseId: coerceInt(ex.exercise_id),
1478
1633
  title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
1479
1634
  instruction: str$1(ex.instruction),
@@ -1496,8 +1651,9 @@ function mergeAthleteWorkout(raw) {
1496
1651
  const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
1497
1652
  const logged = savedSets(saved);
1498
1653
  const performedById = performedSlotsByExerciseId(logged);
1654
+ const savedById = savedRowsByTemplateId(logged);
1499
1655
  const notesById = notesByTemplateId(logged);
1500
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
1656
+ const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, savedById, notesById)).sort((a, b) => a.order - b.order);
1501
1657
  const prescribedIds = /* @__PURE__ */ new Set();
1502
1658
  for (const s of prescriptionSets) {
1503
1659
  const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
@@ -1509,7 +1665,7 @@ function mergeAthleteWorkout(raw) {
1509
1665
  }
1510
1666
  for (const { set, exercises } of logged) {
1511
1667
  const extra = exercises.filter((ex) => {
1512
- if (slotValues(ex, true).size === 0) return false;
1668
+ if (slotValues(ex, false).size === 0) return false;
1513
1669
  const id = coerceInt(ex.workout_set_exercise_id);
1514
1670
  return id === null || !prescribedIds.has(id);
1515
1671
  });
@@ -1685,6 +1841,16 @@ function presentLogTargets(list) {
1685
1841
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1686
1842
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1687
1843
  if (!saved) continue;
1844
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1845
+ const templatesById = /* @__PURE__ */ new Map();
1846
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1847
+ if (!isRecord(tSet)) continue;
1848
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
1849
+ for (const tEx of tExs) {
1850
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
1851
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
1852
+ }
1853
+ }
1688
1854
  const date = str$1(rec.date) ?? "";
1689
1855
  const workoutTitle = str$1(rec.workout_title) ?? "";
1690
1856
  const program = str$1(rec.program_title);
@@ -1699,12 +1865,14 @@ function presentLogTargets(list) {
1699
1865
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1700
1866
  const id = coerceInt(ex.id);
1701
1867
  if (id === null) return null;
1868
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1869
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
1702
1870
  return {
1703
1871
  savedWorkoutSetExerciseId: id,
1704
1872
  title: exerciseTitle(ex),
1705
1873
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1706
1874
  notes: str$1(ex.notes),
1707
- prescribed: prescribedStrings(ex),
1875
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
1708
1876
  performed: performedStrings(ex)
1709
1877
  };
1710
1878
  }).filter((e) => e !== null);
@@ -1829,6 +1997,28 @@ function presentExerciseHistory(detail) {
1829
1997
  };
1830
1998
  }
1831
1999
  //#endregion
2000
+ //#region ../js/src/exercise-history.ts
2001
+ /**
2002
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
2003
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
2004
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
2005
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
2006
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
2007
+ */
2008
+ function historyInRange(presented, since, until) {
2009
+ if (since === void 0 && until === void 0) return presented;
2010
+ const sessions = presented.sessions.filter((s) => {
2011
+ const d = (s.date ?? "").slice(0, 10);
2012
+ if (since !== void 0 && d < since) return false;
2013
+ if (until !== void 0 && d > until) return false;
2014
+ return true;
2015
+ });
2016
+ return {
2017
+ ...presented,
2018
+ sessions
2019
+ };
2020
+ }
2021
+ //#endregion
1832
2022
  //#region ../js/src/coach-athlete-calendar.ts
1833
2023
  async function getArray(client, path, label) {
1834
2024
  const res = await client.request("GET", path);
@@ -1963,6 +2153,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1963
2153
  }
1964
2154
  //#endregion
1965
2155
  //#region ../js/src/athlete-set-write.ts
2156
+ const WRITE_CONCURRENCY = 4;
1966
2157
  /**
1967
2158
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1968
2159
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -2204,6 +2395,41 @@ async function swapAthleteExercise(client, args) {
2204
2395
  originalTeamExerciseId: coerceInt(template.exercise_id)
2205
2396
  };
2206
2397
  }
2398
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
2399
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2400
+ assertUniqueExerciseResults(results);
2401
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2402
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2403
+ return {
2404
+ savedWorkoutSetId,
2405
+ exercises,
2406
+ rawSet,
2407
+ suffix,
2408
+ extra,
2409
+ writes: results.map((result) => {
2410
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
2411
+ if (!ex) {
2412
+ const valid = exercises.map((candidate) => {
2413
+ const id = coerceInt(candidate.id);
2414
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
2415
+ }).filter((label) => label !== null);
2416
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2417
+ }
2418
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2419
+ 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.`);
2420
+ return {
2421
+ id: result.savedWorkoutSetExerciseId,
2422
+ body: {
2423
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2424
+ ...extra
2425
+ }
2426
+ };
2427
+ })
2428
+ };
2429
+ }
2430
+ function errorMessage(error) {
2431
+ return error instanceof Error ? error.message : String(error);
2432
+ }
2207
2433
  /**
2208
2434
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
2209
2435
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -2217,36 +2443,40 @@ async function swapAthleteExercise(client, args) {
2217
2443
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
2218
2444
  * open.
2219
2445
  */
2220
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
2221
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2222
- assertUniqueExerciseResults(results);
2223
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2224
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2225
- let exercisesWritten = 0;
2226
- const projectedCompletion = /* @__PURE__ */ new Map();
2227
- for (const result of results) {
2228
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
2229
- if (!ex) {
2230
- const valid = exercises.map((e) => {
2231
- const id = coerceInt(e.id);
2232
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
2233
- }).filter((x) => x !== null);
2234
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2235
- }
2236
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2237
- 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.`);
2238
- const body = {
2239
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2240
- ...extra
2446
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
2447
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
2448
+ const put = (path, body, failureMessage, finalizer = false) => {
2449
+ const request = async () => {
2450
+ try {
2451
+ const res = await client.request("PUT", path, { body });
2452
+ if (!res.ok) throw new Error(failureMessage(res.status));
2453
+ } catch (error) {
2454
+ limit.cancel(error);
2455
+ throw error;
2456
+ }
2241
2457
  };
2242
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
2243
- if (!res.ok) {
2244
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
2245
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
2246
- }
2247
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
2248
- exercisesWritten += 1;
2458
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
2459
+ };
2460
+ const confirmed = [];
2461
+ try {
2462
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
2463
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
2464
+ return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
2465
+ });
2466
+ confirmed.push(id);
2467
+ if (sessionProgress) {
2468
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
2469
+ sessionConfirmed.push(id);
2470
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
2471
+ }
2472
+ });
2473
+ } catch (error) {
2474
+ if (sessionProgress || confirmed.length === 0) throw error;
2475
+ confirmed.sort((a, b) => a - b);
2476
+ throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
2249
2477
  }
2478
+ const exercisesWritten = writes.length;
2479
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
2250
2480
  let setCompleted = false;
2251
2481
  if (mode === "log") {
2252
2482
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -2254,8 +2484,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2254
2484
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
2255
2485
  ...extra
2256
2486
  };
2257
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
2258
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
2487
+ try {
2488
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
2489
+ } catch (error) {
2490
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
2491
+ }
2259
2492
  setCompleted = true;
2260
2493
  }
2261
2494
  }
@@ -2265,6 +2498,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2265
2498
  setCompleted
2266
2499
  };
2267
2500
  }
2501
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
2502
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
2503
+ }
2268
2504
  /**
2269
2505
  * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
2270
2506
  * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
@@ -2437,7 +2673,7 @@ function prescribedExerciseLabels(workouts) {
2437
2673
  return labels;
2438
2674
  }
2439
2675
  /** Group resolved exercises by saved set and write each set via the given log target. */
2440
- async function logResolvedExercises(client, target, workouts, resolved) {
2676
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
2441
2677
  const bySet = /* @__PURE__ */ new Map();
2442
2678
  for (const r of resolved) {
2443
2679
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -2447,15 +2683,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
2447
2683
  });
2448
2684
  bySet.set(r.savedWorkoutSetId, list);
2449
2685
  }
2450
- const out = [];
2451
- for (const [savedWorkoutSetId, results] of bySet) {
2452
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
2453
- out.push({
2454
- savedWorkoutSetId: written.savedWorkoutSetId,
2455
- exercisesLogged: written.exercisesWritten
2686
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
2687
+ const limit = createLimiter(WRITE_CONCURRENCY);
2688
+ const confirmedBySet = /* @__PURE__ */ new Map();
2689
+ const succeeded = [];
2690
+ try {
2691
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
2692
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
2693
+ succeeded.push(written.savedWorkoutSetId);
2694
+ return {
2695
+ savedWorkoutSetId: written.savedWorkoutSetId,
2696
+ exercisesLogged: written.exercisesWritten
2697
+ };
2456
2698
  });
2699
+ } catch (error) {
2700
+ const completed = new Set(succeeded);
2701
+ const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
2702
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
2703
+ succeeded.sort((a, b) => a - b);
2704
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
2705
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
2706
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
2457
2707
  }
2458
- return out;
2459
2708
  }
2460
2709
  /**
2461
2710
  * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
@@ -2528,7 +2777,7 @@ async function logSessionForAthlete(client, args) {
2528
2777
  const sets = await logResolvedExercises(client, {
2529
2778
  role: "coach",
2530
2779
  athleteId: args.athleteId
2531
- }, day, resolved);
2780
+ }, day, resolved, "Retry the same request to reconcile them.");
2532
2781
  return {
2533
2782
  date: args.date,
2534
2783
  created: false,
@@ -2822,9 +3071,75 @@ function repsList(ex) {
2822
3071
  const reps = ex.reps;
2823
3072
  if (Array.isArray(reps)) return reps.map((r) => String(r));
2824
3073
  if (reps === void 0 || reps === null) return [];
2825
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
3074
+ const sets = Array.isArray(ex.weight) ? ex.weight.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2826
3075
  return Array.from({ length: sets }, () => String(reps));
2827
3076
  }
3077
+ /** Number of sets that the encoder will write for an exercise. */
3078
+ function exerciseSetCount(ex) {
3079
+ if (Array.isArray(ex.reps) && ex.reps.length > 0) return ex.reps.length;
3080
+ if (Array.isArray(ex.weight)) return ex.weight.length;
3081
+ if (!Array.isArray(ex.reps) && ex.reps !== void 0 && ex.reps !== null || ex.weight !== void 0 && ex.weight !== null) return Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
3082
+ return 0;
3083
+ }
3084
+ function findSetSplits(blocks) {
3085
+ return blocks.flatMap((block) => block.exercises.flatMap((exercise) => {
3086
+ const setCount = exerciseSetCount(exercise);
3087
+ if (setCount <= 10) return [];
3088
+ return [{
3089
+ blockTitle: block.title,
3090
+ exerciseTitle: exercise.title ?? String(exercise.id),
3091
+ setCount,
3092
+ blockCount: Math.ceil(setCount / 10)
3093
+ }];
3094
+ }));
3095
+ }
3096
+ function setSplitSummary(blocks) {
3097
+ const splits = findSetSplits(blocks);
3098
+ if (splits.length === 0) return null;
3099
+ return `TrainHeroic supports at most 10 sets per exercise block. The following will be split into consecutive same-titled blocks: ${splits.map(({ blockTitle, exerciseTitle, setCount, blockCount }) => `${blockTitle} / ${exerciseTitle}: ${setCount} sets into ${blockCount} blocks`).join("; ")}.`;
3100
+ }
3101
+ function sliceExercise(exercise, setCount, start) {
3102
+ if (start > 0 && setCount <= start) return null;
3103
+ const chunkCount = setCount === 0 ? 0 : Math.min(10, Math.max(0, setCount - start));
3104
+ const chunk = { ...exercise };
3105
+ const hasPerSetReps = Array.isArray(exercise.reps) && exercise.reps.length > 0;
3106
+ const hasScalarReps = !Array.isArray(exercise.reps) && exercise.reps !== void 0 && exercise.reps !== null;
3107
+ if (Array.isArray(exercise.reps) && exercise.reps.length > 0) {
3108
+ chunk.reps = exercise.reps.slice(start, start + 10);
3109
+ delete chunk.sets;
3110
+ } else if (hasScalarReps) chunk.sets = chunkCount;
3111
+ if (Array.isArray(exercise.weight)) {
3112
+ chunk.weight = exercise.weight.slice(start, start + 10);
3113
+ if (!hasPerSetReps && !hasScalarReps) delete chunk.sets;
3114
+ } else if (!hasPerSetReps && exercise.weight !== void 0 && exercise.weight !== null) chunk.sets = chunkCount;
3115
+ return chunk;
3116
+ }
3117
+ /**
3118
+ * Split blocks so no encoded exercise exceeds TrainHeroic's ten parameter slots.
3119
+ * Exercises in a superset stay aligned by set range; shorter exercises appear only in
3120
+ * chunks where they still have sets.
3121
+ */
3122
+ function splitOversizedBlocks(blocks) {
3123
+ return blocks.flatMap((block) => {
3124
+ const setCounts = block.exercises.map(exerciseSetCount);
3125
+ const largestSetCount = Math.max(0, ...setCounts);
3126
+ const chunkCount = Math.max(1, Math.ceil(largestSetCount / 10));
3127
+ if (chunkCount === 1) return [block];
3128
+ return Array.from({ length: chunkCount }, (_, index) => {
3129
+ const start = index * 10;
3130
+ const exercises = block.exercises.map((exercise, exerciseIndex) => sliceExercise(exercise, setCounts[exerciseIndex] ?? 0, start)).filter((exercise) => exercise !== null);
3131
+ if (index === 0) return {
3132
+ ...block,
3133
+ exercises
3134
+ };
3135
+ return {
3136
+ title: block.title,
3137
+ ...block.type === void 0 ? {} : { type: block.type },
3138
+ exercises
3139
+ };
3140
+ });
3141
+ });
3142
+ }
2828
3143
  /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2829
3144
  function makeExercise(ex, workoutSetId, order, key) {
2830
3145
  const reps = repsList(ex);
@@ -2832,8 +3147,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2832
3147
  if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2833
3148
  const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2834
3149
  const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2835
- let count = reps.length;
2836
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
3150
+ const count = exerciseSetCount(ex);
2837
3151
  let param2Type;
2838
3152
  let param2Values;
2839
3153
  if (hasWeight) {
@@ -2864,8 +3178,8 @@ function makeExercise(ex, workoutSetId, order, key) {
2864
3178
  eType: "e",
2865
3179
  use_count: 0
2866
3180
  };
2867
- const p1 = slots(reps);
2868
- const p2 = slots(param2Values);
3181
+ const p1 = slots(reps, 10);
3182
+ const p2 = slots(param2Values, 10);
2869
3183
  for (let i = 0; i < 10; i += 1) {
2870
3184
  entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2871
3185
  entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
@@ -2983,7 +3297,10 @@ function createPath(opts) {
2983
3297
  return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2984
3298
  }
2985
3299
  async function buildSession(client, opts) {
2986
- const blocks = z.array(blockSpecSchema).parse(opts.blocks);
3300
+ const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3301
+ const splitSummary = setSplitSummary(validatedBlocks);
3302
+ if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3303
+ const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
2987
3304
  const sess = await req(client, "POST", createPath(opts), {});
2988
3305
  checkResponse(sessionCreateResponseSchema, sess, "session create");
2989
3306
  const workoutId = Number(sess.workout_id);
@@ -3046,7 +3363,7 @@ async function readSession(client, programId, date, pwId) {
3046
3363
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3047
3364
  return {
3048
3365
  pwId,
3049
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
3366
+ date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
3050
3367
  published: pw.published,
3051
3368
  instruction: str(pw.instruction),
3052
3369
  blocks
@@ -3066,14 +3383,13 @@ function readBlock(b) {
3066
3383
  };
3067
3384
  }
3068
3385
  function readExercise(ex) {
3069
- const reps = [];
3070
- const load = [];
3071
- for (let i = 1; i <= 10; i += 1) {
3072
- const r = str(ex[`param_1_data_${i}`]);
3073
- if (r !== "") reps.push(r);
3074
- const w = str(ex[`param_2_data_${i}`]);
3075
- if (w !== "") load.push(w);
3076
- }
3386
+ let last = 0;
3387
+ for (let i = 1; i <= 10; i += 1) if (str(ex[`param_1_data_${i}`]) !== "" || str(ex[`param_2_data_${i}`]) !== "") last = i;
3388
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
3389
+ const repsRaw = slots.map((i) => str(ex[`param_1_data_${i}`]));
3390
+ const loadRaw = slots.map((i) => str(ex[`param_2_data_${i}`]));
3391
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
3392
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
3077
3393
  return {
3078
3394
  order: Number(ex.order),
3079
3395
  title: str(ex.title),
@@ -3647,8 +3963,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3647
3963
  } catch {
3648
3964
  workouts = [];
3649
3965
  }
3650
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
3651
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
3966
+ for (const ex of performedExercises(workouts)) {
3652
3967
  const family = classifyMainLift(ex.title);
3653
3968
  if (family === null) continue;
3654
3969
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3893,6 +4208,7 @@ var ExerciseLibrary = class {
3893
4208
  #byId = /* @__PURE__ */ new Map();
3894
4209
  #loaded = false;
3895
4210
  #fetchedAt = 0;
4211
+ #loading = null;
3896
4212
  constructor(client, cache = new MemoryLibraryCache()) {
3897
4213
  this.#client = client;
3898
4214
  this.#cache = cache;
@@ -3920,8 +4236,11 @@ var ExerciseLibrary = class {
3920
4236
  });
3921
4237
  }
3922
4238
  async ensureFresh() {
3923
- if (!this.#loaded) await this.#ensureLoaded();
3924
- else if (Date.now() - this.#fetchedAt > TTL_MS$1) await this.refresh();
4239
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS$1) return;
4240
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
4241
+ this.#loading = null;
4242
+ });
4243
+ await this.#loading;
3925
4244
  }
3926
4245
  async refresh() {
3927
4246
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -3940,6 +4259,7 @@ var ExerciseLibrary = class {
3940
4259
  return presentExercise(s.raw);
3941
4260
  }
3942
4261
  async defaultsMany(ids) {
4262
+ await this.ensureFresh();
3943
4263
  const result = /* @__PURE__ */ new Map();
3944
4264
  for (const id of ids) {
3945
4265
  const s = this.#byId.get(id);
@@ -4060,6 +4380,26 @@ function looksLikeJson(s) {
4060
4380
  function requireTeamCalendarReassignmentConfirmation(teamId, groupProgram, confirmed) {
4061
4381
  if (groupProgram !== void 0 && !confirmed) throw new Error(`reassigning team ${teamId}'s calendar changes live athlete programming; add --yes.`);
4062
4382
  }
4383
+ /**
4384
+ * An integer argument. `Number("")` is 0 and `Number("1.5")` is finite, so a bare `Number` check
4385
+ * let a trailing comma in an id list become id 0 and a fractional --limit slip through; every
4386
+ * integer-valued flag and positional (ids, counts, pages) goes through here instead.
4387
+ */
4388
+ function parseIntArg(value, label) {
4389
+ const s = value.trim();
4390
+ if (!/^-?\d+$/u.test(s)) throw new Error(`${label} must be an integer, got "${value}".`);
4391
+ return Number(s);
4392
+ }
4393
+ /** A positive integer argument (a --limit, a page size): 0 and negatives are rejected. */
4394
+ function parseCountArg(value, label) {
4395
+ const n = parseIntArg(value, label);
4396
+ if (n < 1) throw new Error(`${label} must be a positive integer, got "${value}".`);
4397
+ return n;
4398
+ }
4399
+ /** A comma-separated list of integer ids; a blank entry (e.g. a trailing comma) is an error. */
4400
+ function parseIdList(value, label) {
4401
+ return value.split(",").map((s) => parseIntArg(s, label));
4402
+ }
4063
4403
  //#endregion
4064
4404
  //#region src/session-cache.ts
4065
4405
  const TTL_MS = 216e5;
@@ -4105,7 +4445,7 @@ Coach — manage a roster (needs a coach account):
4105
4445
  coach program <id> | team <id> | team-codes <id>
4106
4446
 
4107
4447
  roster athlete reads (three lenses — pick by the question):
4108
- 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'.
4448
+ coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency with each athlete's session count + training volume; --metric reports the totals in kg instead of lb. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
4109
4449
  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.
4110
4450
  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
4111
4451
  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)
@@ -4161,7 +4501,7 @@ Coach — manage a roster (needs a coach account):
4161
4501
  coach session-template-create --title "..." [--instruction "..."]
4162
4502
  coach session-template-delete --id <id> --yes
4163
4503
 
4164
- analytics (curated metrics; for team training volume/recency use roster-activity --metric instead):
4504
+ analytics (curated metrics; for team training volume/recency use roster-activity instead):
4165
4505
  coach analytics-query [--metric <key>] [--team <id>] [--users id,id] [--exercise <id>] [--date|--start|--end Y-M-D] [--use-metric]
4166
4506
  run with no --metric to list the valid keys + each one's scope and required params
4167
4507
  (these keys are curated and differ from the raw 'coach analytics' categories)
@@ -4178,7 +4518,8 @@ Coach — manage a roster (needs a coach account):
4178
4518
  coach exercise stats
4179
4519
 
4180
4520
  workouts (spec: {"blocks":[{"title","exercises":[{"id","sets"?,"reps"?,"weight"?,"rpe"?}]}],"instruction"?};
4181
- reps/weight may be a scalar or per-set array; omit --publish to leave a draft):
4521
+ reps/weight may be a scalar or per-set array; >10 sets split into consecutive blocks
4522
+ and require --yes; omit --publish to leave a draft):
4182
4523
  coach workout build (--program <id> | --athlete <id>) (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
4183
4524
  coach workout read --program <id> --date Y-M-D --pw <id>
4184
4525
  coach workout publish --pw <id> --yes
@@ -4237,9 +4578,12 @@ function need(value, usage) {
4237
4578
  return value;
4238
4579
  }
4239
4580
  function toInt(value, label) {
4240
- const n = Number(value);
4241
- if (!Number.isFinite(n)) fail(`${label} must be a number, got "${value}".`);
4242
- return n;
4581
+ return parseIntArg(value, label);
4582
+ }
4583
+ /** A --limit style count: a positive integer, so 0 / negatives fail instead of emptying or
4584
+ * tail-slicing the result. Matches the MCP tools' `positive()` limit schemas. */
4585
+ function toCount(value, label) {
4586
+ return parseCountArg(value, label);
4243
4587
  }
4244
4588
  /** Validate input against a dto schema, failing with a readable message on mismatch. */
4245
4589
  function validate(schema, value, label, hint) {
@@ -4292,7 +4636,7 @@ async function mutate(client, method, path, body) {
4292
4636
  }
4293
4637
  /** Parse a comma-separated id list ("1,2,3") into numbers. */
4294
4638
  function idList(value, label) {
4295
- return value.split(",").map((s) => toInt(s.trim(), label));
4639
+ return parseIdList(value, label);
4296
4640
  }
4297
4641
  function library(client) {
4298
4642
  return new ExerciseLibrary(client, new JsonFileLibraryCache());
@@ -4305,7 +4649,7 @@ async function cmdExercise(client, rest) {
4305
4649
  case "search": {
4306
4650
  const { values, positionals } = parse(a, { limit: { type: "string" } });
4307
4651
  const query = need(positionals.join(" ").trim() || void 0, "coach exercise search <query>");
4308
- const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
4652
+ const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : 20;
4309
4653
  return out(await lib.search(query, limit));
4310
4654
  }
4311
4655
  case "get": return out(await lib.get(toInt(need(a[0], "coach exercise get <id>"), "id")));
@@ -4373,12 +4717,15 @@ async function cmdWorkoutBuild(client, a) {
4373
4717
  const parsed = await jsonInput(positionals[0], values.file);
4374
4718
  const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
4375
4719
  const publish = values.publish === true;
4720
+ const splitSummary = setSplitSummary(spec.blocks);
4721
+ if (splitSummary !== null && values.yes !== true) fail(`${splitSummary} Add --yes to confirm.`);
4376
4722
  if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
4377
4723
  const opts = {
4378
4724
  programId,
4379
4725
  blocks: spec.blocks,
4380
4726
  publish
4381
4727
  };
4728
+ if (splitSummary !== null) opts.confirmSetSplit = true;
4382
4729
  if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
4383
4730
  if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
4384
4731
  if (spec.instruction !== void 0) opts.instruction = spec.instruction;
@@ -4445,7 +4792,7 @@ async function cmdMessage(client, rest) {
4445
4792
  limit: { type: "string" },
4446
4793
  after: { type: "string" }
4447
4794
  });
4448
- return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N] [--after <commentId>]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20, values.after !== void 0 ? toInt(values.after, "--after") : void 0));
4795
+ return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N] [--after <commentId>]"), "streamId"), values.limit !== void 0 ? toCount(values.limit, "--limit") : 20, values.after !== void 0 ? toInt(values.after, "--after") : void 0));
4449
4796
  }
4450
4797
  case "draft": {
4451
4798
  const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
@@ -4745,11 +5092,7 @@ async function cmdAthleteWorkouts(client, a) {
4745
5092
  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.");
4746
5093
  const opts = {};
4747
5094
  if (values["logged-only"] === true) opts.loggedOnly = true;
4748
- if (values.limit !== void 0) {
4749
- const limit = toInt(values.limit, "--limit");
4750
- if (!Number.isInteger(limit) || limit < 0) fail(`--limit must be a non-negative integer.`);
4751
- opts.limit = limit;
4752
- }
5095
+ if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
4753
5096
  const workouts = await fetchAthleteWorkoutsChunked(client, start, end);
4754
5097
  if (format !== void 0) return outRaw(serializeWorkoutHistory(selectWorkouts(presentAthleteWorkoutsExport(workouts), opts), format).content);
4755
5098
  if (values["log-ids"] === true) return out(presentLogTargets(workouts));
@@ -4777,9 +5120,15 @@ async function cmdAthlete(client, rest) {
4777
5120
  q: { type: "string" },
4778
5121
  limit: { type: "string" }
4779
5122
  });
4780
- const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
5123
+ const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : void 0;
4781
5124
  const q = values.q;
4782
- return out(q !== void 0 ? await searchExerciseHistory(client, q, limit) : await fetchExerciseHistoryList(client));
5125
+ if (q !== void 0) return out(await searchExerciseHistory(client, q, limit ?? 20));
5126
+ const rows = await fetchExerciseHistoryList(client);
5127
+ if (limit !== void 0 && rows.length > limit) {
5128
+ logErr(`showing ${limit} of ${rows.length} exercises; drop --limit for the full catalog`);
5129
+ return out(rows.slice(0, limit));
5130
+ }
5131
+ return out(rows);
4783
5132
  }
4784
5133
  case "recent-exercises": return out(await fetchRecentExercises(client));
4785
5134
  case "circuits": {
@@ -5008,7 +5357,7 @@ async function cmdCoachAthleteWorkouts(client, a) {
5008
5357
  if (values.raw === true) return out(workouts);
5009
5358
  const opts = {};
5010
5359
  if (values["logged-only"] === true) opts.loggedOnly = true;
5011
- if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
5360
+ if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
5012
5361
  const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
5013
5362
  return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
5014
5363
  }
@@ -5269,16 +5618,12 @@ async function cmdCoachAthleteLiftHistory(client, a) {
5269
5618
  const presented = presentExerciseHistory(detail);
5270
5619
  const since = values.since !== void 0 ? isoDate(values.since, "--since") : void 0;
5271
5620
  const until = values.until !== void 0 ? isoDate(values.until, "--until") : void 0;
5272
- const sessions = presented.sessions.filter((s) => (since === void 0 || s.date >= since) && (until === void 0 || s.date <= until));
5273
- if (sessions.length === 0 && presented.liftPRs.length === 0) return out({
5274
- ...presented,
5275
- sessions,
5621
+ const windowed = historyInRange(presented, since, until);
5622
+ if (windowed.sessions.length === 0 && windowed.liftPRs.length === 0) return out({
5623
+ ...windowed,
5276
5624
  note: `No logged history for exercise ${exerciseId} for athlete ${athleteId}${since !== void 0 || until !== void 0 ? " in this date window" : ""}. This view only shows sessions where the athlete logged this exact exercise — an empty result means none were logged, not an error. Confirm the exercise id (via 'coach exercise resolve <name>') and widen --since/--until.`
5277
5625
  });
5278
- return out({
5279
- ...presented,
5280
- sessions
5281
- });
5626
+ return out(windowed);
5282
5627
  }
5283
5628
  async function cmdCoachMainLiftPrs(client, a) {
5284
5629
  const { values } = parse(a, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "3.5.0",
3
+ "version": "3.5.2",
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": "3.5.0",
25
- "@trainheroic-unofficial/js": "3.5.0"
24
+ "@trainheroic-unofficial/dto": "3.5.2",
25
+ "@trainheroic-unofficial/js": "3.5.2"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.3.0",