@trainheroic-unofficial/cli 3.5.1 → 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.
- package/dist/cli.mjs +396 -129
- package/package.json +3 -3
package/dist/cli.mjs
CHANGED
|
@@ -763,15 +763,19 @@ const workoutSpecSchema = z.object({
|
|
|
763
763
|
/**
|
|
764
764
|
* Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
|
|
765
765
|
* conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
|
|
766
|
-
* as a valid date. Each part must be
|
|
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.
|
|
767
769
|
*/
|
|
768
770
|
function parseWorkoutDate(s) {
|
|
769
|
-
const parts = s.split("-")
|
|
770
|
-
if (parts.length !== 3 || parts.some((
|
|
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}".`);
|
|
771
775
|
return [
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
776
|
+
year,
|
|
777
|
+
month,
|
|
778
|
+
day
|
|
775
779
|
];
|
|
776
780
|
}
|
|
777
781
|
/** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
|
|
@@ -974,6 +978,26 @@ function checkResponse(schema, data, label) {
|
|
|
974
978
|
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
975
979
|
}
|
|
976
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
|
|
977
1001
|
//#region ../js/src/exercise-util.ts
|
|
978
1002
|
/**
|
|
979
1003
|
* Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
|
|
@@ -1147,18 +1171,76 @@ function rankSearch(rows, query, limit) {
|
|
|
1147
1171
|
* on workerd, blowing the subrequest budget.
|
|
1148
1172
|
*/
|
|
1149
1173
|
async function mapPool(items, limit, fn) {
|
|
1174
|
+
assertPositiveInteger(limit, "Concurrency limit");
|
|
1150
1175
|
const out = Array.from({ length: items.length });
|
|
1151
1176
|
let next = 0;
|
|
1177
|
+
const state = { failure: null };
|
|
1152
1178
|
const worker = async () => {
|
|
1153
|
-
while (next < items.length) {
|
|
1179
|
+
while (next < items.length && state.failure === null) {
|
|
1154
1180
|
const i = next;
|
|
1155
1181
|
next += 1;
|
|
1156
|
-
|
|
1182
|
+
try {
|
|
1183
|
+
out[i] = await fn(items[i], i);
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
state.failure ??= { error };
|
|
1186
|
+
}
|
|
1157
1187
|
}
|
|
1158
1188
|
};
|
|
1159
1189
|
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
1190
|
+
if (state.failure !== null) throw state.failure.error;
|
|
1160
1191
|
return out;
|
|
1161
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
|
+
}
|
|
1162
1244
|
//#endregion
|
|
1163
1245
|
//#region ../js/src/athlete.ts
|
|
1164
1246
|
async function getJson(client, path, label) {
|
|
@@ -1212,39 +1294,25 @@ function sortRosterByRecency(rows) {
|
|
|
1212
1294
|
* summary becomes a null-data row (sorted last), not an error.
|
|
1213
1295
|
*/
|
|
1214
1296
|
async function fetchRosterActivity(client, athleteIds, useMetric = false) {
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
try {
|
|
1222
|
-
return {
|
|
1223
|
-
id,
|
|
1224
|
-
summary: await fetchAthleteProfileSummary(client, id, useMetric)
|
|
1225
|
-
};
|
|
1226
|
-
} catch {
|
|
1227
|
-
return {
|
|
1228
|
-
id,
|
|
1229
|
-
summary: null
|
|
1230
|
-
};
|
|
1231
|
-
}
|
|
1232
|
-
}));
|
|
1233
|
-
for (const { id, summary } of settled) {
|
|
1234
|
-
const count = summary?.sessions_count ?? null;
|
|
1235
|
-
const hasSessions = count !== null && count > 0;
|
|
1236
|
-
const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
|
|
1237
|
-
rows.push({
|
|
1238
|
-
athleteId: id,
|
|
1239
|
-
sessionsCount: count,
|
|
1240
|
-
firstLoggedDate: normDate(summary?.first_logged_date),
|
|
1241
|
-
lastLoggedDate: normDate(summary?.last_logged_date),
|
|
1242
|
-
totalReps: summary?.reps_sum ?? null,
|
|
1243
|
-
totalVolume: summary?.volume_sum ?? null
|
|
1244
|
-
});
|
|
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;
|
|
1245
1303
|
}
|
|
1246
|
-
|
|
1247
|
-
|
|
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
|
+
}));
|
|
1248
1316
|
}
|
|
1249
1317
|
function fetchAthletePrefs(client) {
|
|
1250
1318
|
return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
|
|
@@ -1264,9 +1332,19 @@ function fetchAthleteCircuits(client, kind = "recent") {
|
|
|
1264
1332
|
function fetchAthleteProgrammingPrograms(client) {
|
|
1265
1333
|
return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
|
|
1266
1334
|
}
|
|
1267
|
-
/**
|
|
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
|
+
*/
|
|
1268
1341
|
async function searchExerciseHistory(client, query, limit = 20) {
|
|
1269
|
-
|
|
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);
|
|
1270
1348
|
}
|
|
1271
1349
|
function fetchExerciseHistoryDetail(client, exerciseId, userId) {
|
|
1272
1350
|
return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
|
|
@@ -1381,6 +1459,28 @@ function slotValues(ex, requireMade) {
|
|
|
1381
1459
|
}
|
|
1382
1460
|
return map;
|
|
1383
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
|
+
}
|
|
1384
1484
|
/** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
|
|
1385
1485
|
function fmtSlot(slot) {
|
|
1386
1486
|
const has1 = slot.p1 !== null;
|
|
@@ -1390,10 +1490,6 @@ function fmtSlot(slot) {
|
|
|
1390
1490
|
if (has2) return `@ ${slot.p2}`;
|
|
1391
1491
|
return "";
|
|
1392
1492
|
}
|
|
1393
|
-
/** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
|
|
1394
|
-
function prescribedStrings(ex) {
|
|
1395
|
-
return [...slotValues(ex, false).values()].map(fmtSlot);
|
|
1396
|
-
}
|
|
1397
1493
|
/** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
|
|
1398
1494
|
function performedStrings(ex) {
|
|
1399
1495
|
return [...slotValues(ex, true).values()].map(fmtSlot);
|
|
@@ -1415,6 +1511,46 @@ function savedSets(saved) {
|
|
|
1415
1511
|
return out;
|
|
1416
1512
|
}
|
|
1417
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
|
+
/**
|
|
1418
1554
|
* Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
|
|
1419
1555
|
* the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
|
|
1420
1556
|
* entered values live in the same `param_N_data` slots as a prescription.
|
|
@@ -1429,6 +1565,15 @@ function performedSlotsByExerciseId(sets) {
|
|
|
1429
1565
|
}
|
|
1430
1566
|
return map;
|
|
1431
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
|
+
}
|
|
1432
1577
|
/** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
|
|
1433
1578
|
function notesByTemplateId(sets) {
|
|
1434
1579
|
const map = /* @__PURE__ */ new Map();
|
|
@@ -1452,7 +1597,7 @@ function mergeExercise(prescribed, performed, meta) {
|
|
|
1452
1597
|
};
|
|
1453
1598
|
}
|
|
1454
1599
|
/** A prescription block, each exercise aligned with the slots the athlete logged against it. */
|
|
1455
|
-
function mergePrescriptionBlock(set, performedById, notesById) {
|
|
1600
|
+
function mergePrescriptionBlock(set, performedById, savedById, notesById) {
|
|
1456
1601
|
const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
|
|
1457
1602
|
return {
|
|
1458
1603
|
order: coerceInt(set.order) ?? 0,
|
|
@@ -1462,7 +1607,7 @@ function mergePrescriptionBlock(set, performedById, notesById) {
|
|
|
1462
1607
|
exercises: exercises.filter(isRecord).map((ex) => {
|
|
1463
1608
|
const id = coerceInt(ex.id);
|
|
1464
1609
|
const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
|
|
1465
|
-
return mergeExercise(
|
|
1610
|
+
return mergeExercise(prescriptionSlots(ex, id !== null ? savedById.get(id) : void 0), performed, {
|
|
1466
1611
|
exerciseId: coerceInt(ex.exercise_id),
|
|
1467
1612
|
title: typeof ex.title === "string" ? ex.title : "",
|
|
1468
1613
|
instruction: str$1(ex.instruction),
|
|
@@ -1472,14 +1617,18 @@ function mergePrescriptionBlock(set, performedById, notesById) {
|
|
|
1472
1617
|
})
|
|
1473
1618
|
};
|
|
1474
1619
|
}
|
|
1475
|
-
/**
|
|
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
|
+
*/
|
|
1476
1625
|
function mergeSavedBlock(set, exercises) {
|
|
1477
1626
|
return {
|
|
1478
1627
|
order: coerceInt(set.order) ?? 0,
|
|
1479
1628
|
title: str$1(set.title),
|
|
1480
1629
|
instruction: str$1(set.instruction),
|
|
1481
1630
|
isTest: coerceInt(set.is_test) === 1,
|
|
1482
|
-
exercises: exercises.map((ex) => mergeExercise(
|
|
1631
|
+
exercises: exercises.map((ex) => mergeExercise(prescriptionSlots(void 0, ex), slotValues(ex, true), {
|
|
1483
1632
|
exerciseId: coerceInt(ex.exercise_id),
|
|
1484
1633
|
title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
|
|
1485
1634
|
instruction: str$1(ex.instruction),
|
|
@@ -1502,8 +1651,9 @@ function mergeAthleteWorkout(raw) {
|
|
|
1502
1651
|
const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
|
|
1503
1652
|
const logged = savedSets(saved);
|
|
1504
1653
|
const performedById = performedSlotsByExerciseId(logged);
|
|
1654
|
+
const savedById = savedRowsByTemplateId(logged);
|
|
1505
1655
|
const notesById = notesByTemplateId(logged);
|
|
1506
|
-
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);
|
|
1507
1657
|
const prescribedIds = /* @__PURE__ */ new Set();
|
|
1508
1658
|
for (const s of prescriptionSets) {
|
|
1509
1659
|
const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
@@ -1515,7 +1665,7 @@ function mergeAthleteWorkout(raw) {
|
|
|
1515
1665
|
}
|
|
1516
1666
|
for (const { set, exercises } of logged) {
|
|
1517
1667
|
const extra = exercises.filter((ex) => {
|
|
1518
|
-
if (slotValues(ex,
|
|
1668
|
+
if (slotValues(ex, false).size === 0) return false;
|
|
1519
1669
|
const id = coerceInt(ex.workout_set_exercise_id);
|
|
1520
1670
|
return id === null || !prescribedIds.has(id);
|
|
1521
1671
|
});
|
|
@@ -1691,6 +1841,16 @@ function presentLogTargets(list) {
|
|
|
1691
1841
|
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1692
1842
|
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
1693
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
|
+
}
|
|
1694
1854
|
const date = str$1(rec.date) ?? "";
|
|
1695
1855
|
const workoutTitle = str$1(rec.workout_title) ?? "";
|
|
1696
1856
|
const program = str$1(rec.program_title);
|
|
@@ -1705,12 +1865,14 @@ function presentLogTargets(list) {
|
|
|
1705
1865
|
const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
|
|
1706
1866
|
const id = coerceInt(ex.id);
|
|
1707
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);
|
|
1708
1870
|
return {
|
|
1709
1871
|
savedWorkoutSetExerciseId: id,
|
|
1710
1872
|
title: exerciseTitle(ex),
|
|
1711
1873
|
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
1712
1874
|
notes: str$1(ex.notes),
|
|
1713
|
-
prescribed:
|
|
1875
|
+
prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
|
|
1714
1876
|
performed: performedStrings(ex)
|
|
1715
1877
|
};
|
|
1716
1878
|
}).filter((e) => e !== null);
|
|
@@ -1835,6 +1997,28 @@ function presentExerciseHistory(detail) {
|
|
|
1835
1997
|
};
|
|
1836
1998
|
}
|
|
1837
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
|
|
1838
2022
|
//#region ../js/src/coach-athlete-calendar.ts
|
|
1839
2023
|
async function getArray(client, path, label) {
|
|
1840
2024
|
const res = await client.request("GET", path);
|
|
@@ -1969,6 +2153,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
|
|
|
1969
2153
|
}
|
|
1970
2154
|
//#endregion
|
|
1971
2155
|
//#region ../js/src/athlete-set-write.ts
|
|
2156
|
+
const WRITE_CONCURRENCY = 4;
|
|
1972
2157
|
/**
|
|
1973
2158
|
* Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
|
|
1974
2159
|
* {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
|
|
@@ -2210,6 +2395,41 @@ async function swapAthleteExercise(client, args) {
|
|
|
2210
2395
|
originalTeamExerciseId: coerceInt(template.exercise_id)
|
|
2211
2396
|
};
|
|
2212
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
|
+
}
|
|
2213
2433
|
/**
|
|
2214
2434
|
* Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
|
|
2215
2435
|
* {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
|
|
@@ -2223,36 +2443,40 @@ async function swapAthleteExercise(client, args) {
|
|
|
2223
2443
|
* the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
|
|
2224
2444
|
* open.
|
|
2225
2445
|
*/
|
|
2226
|
-
async function
|
|
2227
|
-
const { exercises, rawSet } =
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
const id = coerceInt(e.id);
|
|
2238
|
-
return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
|
|
2239
|
-
}).filter((x) => x !== null);
|
|
2240
|
-
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
2241
|
-
}
|
|
2242
|
-
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
2243
|
-
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.`);
|
|
2244
|
-
const body = {
|
|
2245
|
-
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
|
|
2246
|
-
...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
|
+
}
|
|
2247
2457
|
};
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
}
|
|
2253
|
-
|
|
2254
|
-
|
|
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 });
|
|
2255
2477
|
}
|
|
2478
|
+
const exercisesWritten = writes.length;
|
|
2479
|
+
const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
|
|
2256
2480
|
let setCompleted = false;
|
|
2257
2481
|
if (mode === "log") {
|
|
2258
2482
|
if (isSetFullyLogged(exercises, projectedCompletion)) {
|
|
@@ -2260,8 +2484,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
2260
2484
|
...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
|
|
2261
2485
|
...extra
|
|
2262
2486
|
};
|
|
2263
|
-
|
|
2264
|
-
|
|
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
|
+
}
|
|
2265
2492
|
setCompleted = true;
|
|
2266
2493
|
}
|
|
2267
2494
|
}
|
|
@@ -2271,6 +2498,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
2271
2498
|
setCompleted
|
|
2272
2499
|
};
|
|
2273
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
|
+
}
|
|
2274
2504
|
/**
|
|
2275
2505
|
* POST /v5/programWorkouts/personal — create a personal workout session for a given date.
|
|
2276
2506
|
* Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
|
|
@@ -2443,7 +2673,7 @@ function prescribedExerciseLabels(workouts) {
|
|
|
2443
2673
|
return labels;
|
|
2444
2674
|
}
|
|
2445
2675
|
/** Group resolved exercises by saved set and write each set via the given log target. */
|
|
2446
|
-
async function logResolvedExercises(client, target, workouts, resolved) {
|
|
2676
|
+
async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
|
|
2447
2677
|
const bySet = /* @__PURE__ */ new Map();
|
|
2448
2678
|
for (const r of resolved) {
|
|
2449
2679
|
const list = bySet.get(r.savedWorkoutSetId) ?? [];
|
|
@@ -2453,15 +2683,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
|
|
|
2453
2683
|
});
|
|
2454
2684
|
bySet.set(r.savedWorkoutSetId, list);
|
|
2455
2685
|
}
|
|
2456
|
-
const
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
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
|
+
};
|
|
2462
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 });
|
|
2463
2707
|
}
|
|
2464
|
-
return out;
|
|
2465
2708
|
}
|
|
2466
2709
|
/**
|
|
2467
2710
|
* Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
|
|
@@ -2534,7 +2777,7 @@ async function logSessionForAthlete(client, args) {
|
|
|
2534
2777
|
const sets = await logResolvedExercises(client, {
|
|
2535
2778
|
role: "coach",
|
|
2536
2779
|
athleteId: args.athleteId
|
|
2537
|
-
}, day, resolved);
|
|
2780
|
+
}, day, resolved, "Retry the same request to reconcile them.");
|
|
2538
2781
|
return {
|
|
2539
2782
|
date: args.date,
|
|
2540
2783
|
created: false,
|
|
@@ -3120,7 +3363,7 @@ async function readSession(client, programId, date, pwId) {
|
|
|
3120
3363
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
3121
3364
|
return {
|
|
3122
3365
|
pwId,
|
|
3123
|
-
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")}`,
|
|
3124
3367
|
published: pw.published,
|
|
3125
3368
|
instruction: str(pw.instruction),
|
|
3126
3369
|
blocks
|
|
@@ -3140,14 +3383,13 @@ function readBlock(b) {
|
|
|
3140
3383
|
};
|
|
3141
3384
|
}
|
|
3142
3385
|
function readExercise(ex) {
|
|
3143
|
-
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
|
|
3150
|
-
}
|
|
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 : [];
|
|
3151
3393
|
return {
|
|
3152
3394
|
order: Number(ex.order),
|
|
3153
3395
|
title: str(ex.title),
|
|
@@ -3721,8 +3963,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
|
3721
3963
|
} catch {
|
|
3722
3964
|
workouts = [];
|
|
3723
3965
|
}
|
|
3724
|
-
for (const
|
|
3725
|
-
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
3966
|
+
for (const ex of performedExercises(workouts)) {
|
|
3726
3967
|
const family = classifyMainLift(ex.title);
|
|
3727
3968
|
if (family === null) continue;
|
|
3728
3969
|
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
@@ -3967,6 +4208,7 @@ var ExerciseLibrary = class {
|
|
|
3967
4208
|
#byId = /* @__PURE__ */ new Map();
|
|
3968
4209
|
#loaded = false;
|
|
3969
4210
|
#fetchedAt = 0;
|
|
4211
|
+
#loading = null;
|
|
3970
4212
|
constructor(client, cache = new MemoryLibraryCache()) {
|
|
3971
4213
|
this.#client = client;
|
|
3972
4214
|
this.#cache = cache;
|
|
@@ -3994,8 +4236,11 @@ var ExerciseLibrary = class {
|
|
|
3994
4236
|
});
|
|
3995
4237
|
}
|
|
3996
4238
|
async ensureFresh() {
|
|
3997
|
-
if (
|
|
3998
|
-
|
|
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;
|
|
3999
4244
|
}
|
|
4000
4245
|
async refresh() {
|
|
4001
4246
|
const res = await this.#client.request("GET", LIBRARY_PATH);
|
|
@@ -4014,6 +4259,7 @@ var ExerciseLibrary = class {
|
|
|
4014
4259
|
return presentExercise(s.raw);
|
|
4015
4260
|
}
|
|
4016
4261
|
async defaultsMany(ids) {
|
|
4262
|
+
await this.ensureFresh();
|
|
4017
4263
|
const result = /* @__PURE__ */ new Map();
|
|
4018
4264
|
for (const id of ids) {
|
|
4019
4265
|
const s = this.#byId.get(id);
|
|
@@ -4134,6 +4380,26 @@ function looksLikeJson(s) {
|
|
|
4134
4380
|
function requireTeamCalendarReassignmentConfirmation(teamId, groupProgram, confirmed) {
|
|
4135
4381
|
if (groupProgram !== void 0 && !confirmed) throw new Error(`reassigning team ${teamId}'s calendar changes live athlete programming; add --yes.`);
|
|
4136
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
|
+
}
|
|
4137
4403
|
//#endregion
|
|
4138
4404
|
//#region src/session-cache.ts
|
|
4139
4405
|
const TTL_MS = 216e5;
|
|
@@ -4179,7 +4445,7 @@ Coach — manage a roster (needs a coach account):
|
|
|
4179
4445
|
coach program <id> | team <id> | team-codes <id>
|
|
4180
4446
|
|
|
4181
4447
|
roster athlete reads (three lenses — pick by the question):
|
|
4182
|
-
coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency
|
|
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'.
|
|
4183
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.
|
|
4184
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
|
|
4185
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)
|
|
@@ -4235,7 +4501,7 @@ Coach — manage a roster (needs a coach account):
|
|
|
4235
4501
|
coach session-template-create --title "..." [--instruction "..."]
|
|
4236
4502
|
coach session-template-delete --id <id> --yes
|
|
4237
4503
|
|
|
4238
|
-
analytics (curated metrics; for team training volume/recency use roster-activity
|
|
4504
|
+
analytics (curated metrics; for team training volume/recency use roster-activity instead):
|
|
4239
4505
|
coach analytics-query [--metric <key>] [--team <id>] [--users id,id] [--exercise <id>] [--date|--start|--end Y-M-D] [--use-metric]
|
|
4240
4506
|
run with no --metric to list the valid keys + each one's scope and required params
|
|
4241
4507
|
(these keys are curated and differ from the raw 'coach analytics' categories)
|
|
@@ -4312,9 +4578,12 @@ function need(value, usage) {
|
|
|
4312
4578
|
return value;
|
|
4313
4579
|
}
|
|
4314
4580
|
function toInt(value, label) {
|
|
4315
|
-
|
|
4316
|
-
|
|
4317
|
-
|
|
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);
|
|
4318
4587
|
}
|
|
4319
4588
|
/** Validate input against a dto schema, failing with a readable message on mismatch. */
|
|
4320
4589
|
function validate(schema, value, label, hint) {
|
|
@@ -4367,7 +4636,7 @@ async function mutate(client, method, path, body) {
|
|
|
4367
4636
|
}
|
|
4368
4637
|
/** Parse a comma-separated id list ("1,2,3") into numbers. */
|
|
4369
4638
|
function idList(value, label) {
|
|
4370
|
-
return value
|
|
4639
|
+
return parseIdList(value, label);
|
|
4371
4640
|
}
|
|
4372
4641
|
function library(client) {
|
|
4373
4642
|
return new ExerciseLibrary(client, new JsonFileLibraryCache());
|
|
@@ -4380,7 +4649,7 @@ async function cmdExercise(client, rest) {
|
|
|
4380
4649
|
case "search": {
|
|
4381
4650
|
const { values, positionals } = parse(a, { limit: { type: "string" } });
|
|
4382
4651
|
const query = need(positionals.join(" ").trim() || void 0, "coach exercise search <query>");
|
|
4383
|
-
const limit = values.limit !== void 0 ?
|
|
4652
|
+
const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : 20;
|
|
4384
4653
|
return out(await lib.search(query, limit));
|
|
4385
4654
|
}
|
|
4386
4655
|
case "get": return out(await lib.get(toInt(need(a[0], "coach exercise get <id>"), "id")));
|
|
@@ -4523,7 +4792,7 @@ async function cmdMessage(client, rest) {
|
|
|
4523
4792
|
limit: { type: "string" },
|
|
4524
4793
|
after: { type: "string" }
|
|
4525
4794
|
});
|
|
4526
|
-
return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N] [--after <commentId>]"), "streamId"), values.limit !== 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));
|
|
4527
4796
|
}
|
|
4528
4797
|
case "draft": {
|
|
4529
4798
|
const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
|
|
@@ -4823,11 +5092,7 @@ async function cmdAthleteWorkouts(client, a) {
|
|
|
4823
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.");
|
|
4824
5093
|
const opts = {};
|
|
4825
5094
|
if (values["logged-only"] === true) opts.loggedOnly = true;
|
|
4826
|
-
if (values.limit !== void 0)
|
|
4827
|
-
const limit = toInt(values.limit, "--limit");
|
|
4828
|
-
if (!Number.isInteger(limit) || limit < 0) fail(`--limit must be a non-negative integer.`);
|
|
4829
|
-
opts.limit = limit;
|
|
4830
|
-
}
|
|
5095
|
+
if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
|
|
4831
5096
|
const workouts = await fetchAthleteWorkoutsChunked(client, start, end);
|
|
4832
5097
|
if (format !== void 0) return outRaw(serializeWorkoutHistory(selectWorkouts(presentAthleteWorkoutsExport(workouts), opts), format).content);
|
|
4833
5098
|
if (values["log-ids"] === true) return out(presentLogTargets(workouts));
|
|
@@ -4855,9 +5120,15 @@ async function cmdAthlete(client, rest) {
|
|
|
4855
5120
|
q: { type: "string" },
|
|
4856
5121
|
limit: { type: "string" }
|
|
4857
5122
|
});
|
|
4858
|
-
const limit = values.limit !== void 0 ?
|
|
5123
|
+
const limit = values.limit !== void 0 ? toCount(values.limit, "--limit") : void 0;
|
|
4859
5124
|
const q = values.q;
|
|
4860
|
-
|
|
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);
|
|
4861
5132
|
}
|
|
4862
5133
|
case "recent-exercises": return out(await fetchRecentExercises(client));
|
|
4863
5134
|
case "circuits": {
|
|
@@ -5086,7 +5357,7 @@ async function cmdCoachAthleteWorkouts(client, a) {
|
|
|
5086
5357
|
if (values.raw === true) return out(workouts);
|
|
5087
5358
|
const opts = {};
|
|
5088
5359
|
if (values["logged-only"] === true) opts.loggedOnly = true;
|
|
5089
|
-
if (values.limit !== void 0) opts.limit =
|
|
5360
|
+
if (values.limit !== void 0) opts.limit = toCount(values.limit, "--limit");
|
|
5090
5361
|
const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
|
|
5091
5362
|
return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
|
|
5092
5363
|
}
|
|
@@ -5347,16 +5618,12 @@ async function cmdCoachAthleteLiftHistory(client, a) {
|
|
|
5347
5618
|
const presented = presentExerciseHistory(detail);
|
|
5348
5619
|
const since = values.since !== void 0 ? isoDate(values.since, "--since") : void 0;
|
|
5349
5620
|
const until = values.until !== void 0 ? isoDate(values.until, "--until") : void 0;
|
|
5350
|
-
const
|
|
5351
|
-
if (sessions.length === 0 &&
|
|
5352
|
-
...
|
|
5353
|
-
sessions,
|
|
5621
|
+
const windowed = historyInRange(presented, since, until);
|
|
5622
|
+
if (windowed.sessions.length === 0 && windowed.liftPRs.length === 0) return out({
|
|
5623
|
+
...windowed,
|
|
5354
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.`
|
|
5355
5625
|
});
|
|
5356
|
-
return out(
|
|
5357
|
-
...presented,
|
|
5358
|
-
sessions
|
|
5359
|
-
});
|
|
5626
|
+
return out(windowed);
|
|
5360
5627
|
}
|
|
5361
5628
|
async function cmdCoachMainLiftPrs(client, a) {
|
|
5362
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.
|
|
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.
|
|
25
|
-
"@trainheroic-unofficial/js": "3.5.
|
|
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",
|