@trainheroic-unofficial/cli 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -16
- package/dist/cli.mjs +1665 -65
- package/package.json +6 -5
- package/skill/trainheroic-athlete/SKILL.md +148 -0
- package/skill/trainheroic-athlete/references/athlete-api.md +111 -0
- package/skill/trainheroic-unofficial/SKILL.md +275 -0
- package/skill/trainheroic-unofficial/references/api-reference.md +1361 -0
- package/skill/trainheroic-unofficial/references/data-warehouse.md +127 -0
- package/skill/trainheroic-unofficial/references/workout-creation.md +310 -0
package/dist/cli.mjs
CHANGED
|
@@ -1,14 +1,180 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
3
5
|
import process from "node:process";
|
|
4
6
|
import { parseArgs } from "node:util";
|
|
5
7
|
import { z } from "zod";
|
|
6
|
-
import { homedir } from "node:os";
|
|
7
|
-
import { dirname, join } from "node:path";
|
|
8
8
|
//#region ../dto/src/common.ts
|
|
9
9
|
/** An entity id as it arrives over the wire — a number or a numeric string. */
|
|
10
10
|
const idSchema = z.union([z.string(), z.number()]);
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* An id as a tool argument: a number, or a string of digits. Unlike idSchema (which
|
|
13
|
+
* tolerates whatever the API sends back), this rejects non-numeric strings up front so
|
|
14
|
+
* a bad argument fails validation instead of becoming NaN in a URL or a query.
|
|
15
|
+
*/
|
|
16
|
+
const idArgSchema = z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region ../dto/src/athlete.ts
|
|
19
|
+
const intLike$1 = z.union([z.number(), z.string()]);
|
|
20
|
+
const intLikeOrNull$1 = z.union([
|
|
21
|
+
z.number(),
|
|
22
|
+
z.string(),
|
|
23
|
+
z.null()
|
|
24
|
+
]);
|
|
25
|
+
const numLikeOrNull = z.union([
|
|
26
|
+
z.number(),
|
|
27
|
+
z.string(),
|
|
28
|
+
z.null()
|
|
29
|
+
]);
|
|
30
|
+
z.looseObject({
|
|
31
|
+
id: intLike$1,
|
|
32
|
+
roles: z.array(z.string()).optional(),
|
|
33
|
+
org_id: intLikeOrNull$1.optional()
|
|
34
|
+
});
|
|
35
|
+
z.looseObject({
|
|
36
|
+
reps_sum: z.number().optional(),
|
|
37
|
+
volume_sum: z.number().optional(),
|
|
38
|
+
sessions_count: z.number().optional(),
|
|
39
|
+
first_logged_date: z.string().optional(),
|
|
40
|
+
last_logged_date: z.string().optional(),
|
|
41
|
+
duration_hours: z.number().optional()
|
|
42
|
+
});
|
|
43
|
+
z.looseObject({
|
|
44
|
+
id: intLike$1,
|
|
45
|
+
email: z.string().optional(),
|
|
46
|
+
name_first: z.string().optional(),
|
|
47
|
+
name_last: z.string().optional(),
|
|
48
|
+
username: z.string().optional(),
|
|
49
|
+
gender: z.string().optional(),
|
|
50
|
+
date_of_birth: z.string().optional(),
|
|
51
|
+
use_metric: z.boolean().optional()
|
|
52
|
+
});
|
|
53
|
+
z.looseObject({ id: intLike$1 });
|
|
54
|
+
/** One item of `/2.0/athlete/workingMax` — the athlete's working max for an exercise. */
|
|
55
|
+
const athleteWorkingMaxSchema = z.looseObject({
|
|
56
|
+
exercise_id: intLike$1,
|
|
57
|
+
title: z.string().optional(),
|
|
58
|
+
param_type: intLikeOrNull$1.optional(),
|
|
59
|
+
value: numLikeOrNull.optional(),
|
|
60
|
+
type_suffix: z.string().optional(),
|
|
61
|
+
working_max_id: intLikeOrNull$1.optional()
|
|
62
|
+
});
|
|
63
|
+
z.array(athleteWorkingMaxSchema);
|
|
64
|
+
/** One item of `/v5/users/exercises/history` — an exercise the athlete has logged. */
|
|
65
|
+
const exerciseHistoryListItemSchema = z.looseObject({
|
|
66
|
+
id: intLike$1,
|
|
67
|
+
title: z.string(),
|
|
68
|
+
isCircuit: z.boolean().optional(),
|
|
69
|
+
prescription: z.string().optional(),
|
|
70
|
+
param1Type: intLikeOrNull$1.optional(),
|
|
71
|
+
param2Type: intLikeOrNull$1.optional()
|
|
72
|
+
});
|
|
73
|
+
z.array(exerciseHistoryListItemSchema);
|
|
74
|
+
/** A single completed set inside a history entry (`/v5/exercises/{id}/history`). */
|
|
75
|
+
const historySetSchema = z.looseObject({
|
|
76
|
+
setNumber: z.number(),
|
|
77
|
+
formattedValue: z.string().optional(),
|
|
78
|
+
rawValue1: numLikeOrNull.optional(),
|
|
79
|
+
rawValue2: numLikeOrNull.optional(),
|
|
80
|
+
savedWorkoutSetExerciseId: intLike$1.optional()
|
|
81
|
+
});
|
|
82
|
+
/** A best rep-max derived for a history entry. */
|
|
83
|
+
const repMaxSchema = z.looseObject({
|
|
84
|
+
reps: z.number(),
|
|
85
|
+
weight: z.number()
|
|
86
|
+
});
|
|
87
|
+
/** One performed session of an exercise (`/v5/exercises/{id}/history` → `history[]`). */
|
|
88
|
+
const historyEntrySchema = z.looseObject({
|
|
89
|
+
dateCompleted: z.string(),
|
|
90
|
+
notes: z.string().nullable().optional(),
|
|
91
|
+
isLift: z.boolean().optional(),
|
|
92
|
+
param1Type: intLikeOrNull$1.optional(),
|
|
93
|
+
param2Type: intLikeOrNull$1.optional(),
|
|
94
|
+
savedWorkoutSetExerciseId: intLike$1.optional(),
|
|
95
|
+
teamId: intLikeOrNull$1.optional(),
|
|
96
|
+
programWorkoutId: intLikeOrNull$1.optional(),
|
|
97
|
+
abr: z.string().optional(),
|
|
98
|
+
bestEstimated1RM: z.number().optional(),
|
|
99
|
+
repMaxes: z.array(repMaxSchema).optional(),
|
|
100
|
+
sets: z.array(historySetSchema).optional()
|
|
101
|
+
});
|
|
102
|
+
/** A lifetime PR row from `/v5/exercises/{id}/history` → `liftPRs[]`. */
|
|
103
|
+
const liftPRSchema = z.looseObject({
|
|
104
|
+
weight: z.number().optional(),
|
|
105
|
+
savedWorkoutSetExerciseId: intLike$1.optional(),
|
|
106
|
+
setNumber: z.number().optional(),
|
|
107
|
+
dateCompleted: z.string().optional(),
|
|
108
|
+
reps: z.number().optional(),
|
|
109
|
+
units: z.string().optional(),
|
|
110
|
+
isMetric: z.boolean().optional(),
|
|
111
|
+
description: z.string().optional()
|
|
112
|
+
});
|
|
113
|
+
z.looseObject({
|
|
114
|
+
liftPRs: z.array(liftPRSchema).optional(),
|
|
115
|
+
singleParamPRs: z.array(z.unknown()).optional(),
|
|
116
|
+
history: z.array(historyEntrySchema).optional()
|
|
117
|
+
});
|
|
118
|
+
/** One item of `/v5/exercises/{id}/personalRecords` — a standards-filtered PR. */
|
|
119
|
+
const personalRecordSchema = z.looseObject({
|
|
120
|
+
id: intLike$1.optional(),
|
|
121
|
+
savedWorkoutSetExerciseId: intLike$1.optional(),
|
|
122
|
+
setNumber: z.number().optional(),
|
|
123
|
+
reps: z.number().optional(),
|
|
124
|
+
weight: z.number().optional(),
|
|
125
|
+
scaledWeight: z.number().optional(),
|
|
126
|
+
units: z.string().optional(),
|
|
127
|
+
isMetric: z.boolean().optional()
|
|
128
|
+
});
|
|
129
|
+
z.array(personalRecordSchema);
|
|
130
|
+
z.looseObject({
|
|
131
|
+
isLift: z.boolean().optional(),
|
|
132
|
+
lastPerformance: z.unknown().optional(),
|
|
133
|
+
personalRecord: z.unknown().optional()
|
|
134
|
+
});
|
|
135
|
+
/**
|
|
136
|
+
* One item of `/3.0/athlete/programworkout/range` — a scheduled/completed workout. The deep
|
|
137
|
+
* `summarizedSavedWorkout` tree is left loose: the presenter in `js` flattens it, so dto only
|
|
138
|
+
* pins the top-level fields the warehouse and presenter key off.
|
|
139
|
+
*/
|
|
140
|
+
const programWorkoutSchema = z.looseObject({
|
|
141
|
+
id: intLike$1,
|
|
142
|
+
date: z.string().optional(),
|
|
143
|
+
workout_title: z.string().optional(),
|
|
144
|
+
program_id: intLikeOrNull$1.optional(),
|
|
145
|
+
program_title: z.string().optional(),
|
|
146
|
+
team_id: intLikeOrNull$1.optional(),
|
|
147
|
+
team_title: z.string().optional(),
|
|
148
|
+
summarizedSavedWorkout: z.unknown().optional()
|
|
149
|
+
});
|
|
150
|
+
z.array(programWorkoutSchema);
|
|
151
|
+
/** A `YYYY-MM-DD` date argument. The single definition reused across athlete tool inputs. */
|
|
152
|
+
const dateString = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "expected YYYY-MM-DD");
|
|
153
|
+
z.object({
|
|
154
|
+
startDate: dateString,
|
|
155
|
+
endDate: dateString
|
|
156
|
+
});
|
|
157
|
+
/**
|
|
158
|
+
* Args for the set-logging write. `date` (the workout's day) locates the saved
|
|
159
|
+
* workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
|
|
160
|
+
* gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
|
|
161
|
+
*/
|
|
162
|
+
const logSetArgsSchema = z.object({
|
|
163
|
+
date: dateString,
|
|
164
|
+
savedWorkoutSetId: idArgSchema,
|
|
165
|
+
results: z.array(z.object({
|
|
166
|
+
savedWorkoutSetExerciseId: idArgSchema,
|
|
167
|
+
sets: z.array(z.object({
|
|
168
|
+
param1: z.union([z.number(), z.string()]).optional(),
|
|
169
|
+
param2: z.union([z.number(), z.string()]).optional()
|
|
170
|
+
})).min(1)
|
|
171
|
+
})).min(1)
|
|
172
|
+
});
|
|
173
|
+
/**
|
|
174
|
+
* Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
|
|
175
|
+
* roster `athleteId` whose set is being logged on their behalf.
|
|
176
|
+
*/
|
|
177
|
+
const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
|
|
12
178
|
//#endregion
|
|
13
179
|
//#region ../dto/src/exercise.ts
|
|
14
180
|
/** Body for creating a custom exercise; extra fields the API accepts are preserved. */
|
|
@@ -270,12 +436,31 @@ function unitLabel(paramType) {
|
|
|
270
436
|
if (t === null) return null;
|
|
271
437
|
return PARAM_UNIT[t] ?? null;
|
|
272
438
|
}
|
|
273
|
-
/**
|
|
439
|
+
/**
|
|
440
|
+
* Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
|
|
441
|
+
* Positional, not semantic: some exercises reverse the slots, so the array is not labelled
|
|
442
|
+
* by role. A null entry is an unset slot.
|
|
443
|
+
*/
|
|
444
|
+
function exerciseUnits(param1, param2) {
|
|
445
|
+
return [unitLabel(param1), unitLabel(param2)];
|
|
446
|
+
}
|
|
447
|
+
/** Present a row for display: drop the raw param-type codes, surface units positionally. */
|
|
274
448
|
function withUnits(row) {
|
|
449
|
+
const { param_1_type, param_2_type, ...rest } = row;
|
|
275
450
|
return {
|
|
276
|
-
...
|
|
277
|
-
|
|
278
|
-
|
|
451
|
+
...rest,
|
|
452
|
+
units: exerciseUnits(param_1_type, param_2_type)
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Present a full raw exercise object for display: drop the raw param-type codes and add the
|
|
457
|
+
* positional `units` array. Keeps every other field of the raw object intact.
|
|
458
|
+
*/
|
|
459
|
+
function presentExercise$1(raw) {
|
|
460
|
+
const { param_1_type, param_2_type, ...rest } = raw;
|
|
461
|
+
return {
|
|
462
|
+
...rest,
|
|
463
|
+
units: exerciseUnits(param_1_type, param_2_type)
|
|
279
464
|
};
|
|
280
465
|
}
|
|
281
466
|
function buildSearchText(title) {
|
|
@@ -337,13 +522,881 @@ function rankSearch(rows, query, limit) {
|
|
|
337
522
|
if (title.startsWith(q)) score += 100;
|
|
338
523
|
for (const tok of tokens) if (title.includes(tok)) score += 10;
|
|
339
524
|
score -= title.length * .05;
|
|
340
|
-
if (row.can_edit === 0) score += 1;
|
|
525
|
+
if ((row.can_edit ?? 0) === 0) score += 1;
|
|
341
526
|
return {
|
|
342
527
|
row,
|
|
343
528
|
score
|
|
344
529
|
};
|
|
345
530
|
}).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
|
|
346
531
|
}
|
|
532
|
+
/**
|
|
533
|
+
* Map over items with a bounded number of concurrent workers. Used to fan out upstream
|
|
534
|
+
* fetches (per-exercise history, the CLI export) without bursting the host all at once or,
|
|
535
|
+
* on workerd, blowing the subrequest budget.
|
|
536
|
+
*/
|
|
537
|
+
async function mapPool(items, limit, fn) {
|
|
538
|
+
const out = Array.from({ length: items.length });
|
|
539
|
+
let next = 0;
|
|
540
|
+
const worker = async () => {
|
|
541
|
+
while (next < items.length) {
|
|
542
|
+
const i = next;
|
|
543
|
+
next += 1;
|
|
544
|
+
out[i] = await fn(items[i], i);
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
|
|
548
|
+
return out;
|
|
549
|
+
}
|
|
550
|
+
//#endregion
|
|
551
|
+
//#region ../js/src/athlete.ts
|
|
552
|
+
async function getJson(client, path, label) {
|
|
553
|
+
const res = await client.request("GET", path);
|
|
554
|
+
if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
555
|
+
return res.data;
|
|
556
|
+
}
|
|
557
|
+
async function getArray(client, path, label) {
|
|
558
|
+
const res = await client.request("GET", path);
|
|
559
|
+
if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
560
|
+
return res.data;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* The logged-in account's numeric user id (the athlete warehouse's tenant key, and a required
|
|
564
|
+
* query arg for several athlete endpoints). Works from any session — coach or athlete — and
|
|
565
|
+
* even from a cached session that never went through login.
|
|
566
|
+
*/
|
|
567
|
+
async function resolveAthleteUserId(client) {
|
|
568
|
+
const res = await client.request("GET", "/user/simple");
|
|
569
|
+
const id = isRecord(res.data) ? coerceInt(res.data.id) : null;
|
|
570
|
+
if (!res.ok || id === null || id <= 0) throw new Error("Could not resolve athlete user id from /user/simple.");
|
|
571
|
+
return id;
|
|
572
|
+
}
|
|
573
|
+
/** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
|
|
574
|
+
function fetchAthleteProfileSummary(client, userId, useMetric = false) {
|
|
575
|
+
return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
|
|
576
|
+
}
|
|
577
|
+
function fetchAthleteUser(client, userId) {
|
|
578
|
+
return getJson(client, `/v5/users/${userId}`, "athlete user");
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
|
|
582
|
+
* Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
|
|
583
|
+
* left to arbitrary input order.
|
|
584
|
+
*/
|
|
585
|
+
function sortRosterByRecency(rows) {
|
|
586
|
+
return [...rows].sort((a, b) => {
|
|
587
|
+
if (a.lastLoggedDate !== b.lastLoggedDate) {
|
|
588
|
+
if (a.lastLoggedDate === null) return 1;
|
|
589
|
+
if (b.lastLoggedDate === null) return -1;
|
|
590
|
+
return a.lastLoggedDate < b.lastLoggedDate ? 1 : -1;
|
|
591
|
+
}
|
|
592
|
+
return (b.sessionsCount ?? 0) - (a.sessionsCount ?? 0);
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
|
|
597
|
+
* first/last logged date, total reps/volume), sorted most-recently-active first. There is no
|
|
598
|
+
* single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
|
|
599
|
+
* a small concurrency cap; pass the subset you care about for a large org. A failed or missing
|
|
600
|
+
* summary becomes a null-data row (sorted last), not an error.
|
|
601
|
+
*/
|
|
602
|
+
async function fetchRosterActivity(client, athleteIds, useMetric = false) {
|
|
603
|
+
const rows = [];
|
|
604
|
+
const concurrency = 6;
|
|
605
|
+
for (let i = 0; i < athleteIds.length; i += concurrency) {
|
|
606
|
+
const chunk = athleteIds.slice(i, i + concurrency);
|
|
607
|
+
const settled = await Promise.all(chunk.map(async (id) => {
|
|
608
|
+
try {
|
|
609
|
+
return {
|
|
610
|
+
id,
|
|
611
|
+
summary: await fetchAthleteProfileSummary(client, id, useMetric)
|
|
612
|
+
};
|
|
613
|
+
} catch {
|
|
614
|
+
return {
|
|
615
|
+
id,
|
|
616
|
+
summary: null
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
}));
|
|
620
|
+
for (const { id, summary } of settled) {
|
|
621
|
+
const count = summary?.sessions_count ?? null;
|
|
622
|
+
const hasSessions = count !== null && count > 0;
|
|
623
|
+
const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
|
|
624
|
+
rows.push({
|
|
625
|
+
athleteId: id,
|
|
626
|
+
sessionsCount: count,
|
|
627
|
+
firstLoggedDate: normDate(summary?.first_logged_date),
|
|
628
|
+
lastLoggedDate: normDate(summary?.last_logged_date),
|
|
629
|
+
totalReps: summary?.reps_sum ?? null,
|
|
630
|
+
totalVolume: summary?.volume_sum ?? null
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return sortRosterByRecency(rows);
|
|
635
|
+
}
|
|
636
|
+
function fetchAthletePrefs(client) {
|
|
637
|
+
return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
|
|
638
|
+
}
|
|
639
|
+
function fetchWorkingMaxes(client) {
|
|
640
|
+
return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
|
|
641
|
+
}
|
|
642
|
+
function fetchExerciseHistoryList(client) {
|
|
643
|
+
return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
|
|
644
|
+
}
|
|
645
|
+
/** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
|
|
646
|
+
async function searchExerciseHistory(client, query, limit = 20) {
|
|
647
|
+
return rankSearch(await fetchExerciseHistoryList(client), query, limit);
|
|
648
|
+
}
|
|
649
|
+
function fetchExerciseHistoryDetail(client, exerciseId, userId) {
|
|
650
|
+
return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
|
|
651
|
+
}
|
|
652
|
+
function fetchPersonalRecords(client, exerciseId) {
|
|
653
|
+
return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
|
|
654
|
+
}
|
|
655
|
+
/** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
|
|
656
|
+
function fetchExerciseStats(client, exerciseId, userId, date) {
|
|
657
|
+
return getJson(client, `/v5/exercises/${exerciseId}/stats?userId=${userId}&date=${date}`, "athlete exercise stats");
|
|
658
|
+
}
|
|
659
|
+
/** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
|
|
660
|
+
function fetchAthleteWorkouts(client, startDate, endDate) {
|
|
661
|
+
return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
665
|
+
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
666
|
+
* `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
|
|
667
|
+
* `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
|
|
668
|
+
*/
|
|
669
|
+
function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
|
|
670
|
+
return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* A coach's month view of a roster athlete's logged sessions
|
|
674
|
+
* (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
|
|
675
|
+
* ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
|
|
676
|
+
* `userId` in each row is the roster athlete, not the calling coach.
|
|
677
|
+
*/
|
|
678
|
+
function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
|
|
679
|
+
return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
|
|
680
|
+
}
|
|
681
|
+
function fetchLeaderboard(client, workoutId, opts = {}) {
|
|
682
|
+
const qs = new URLSearchParams();
|
|
683
|
+
if (opts.page !== void 0) qs.set("page", String(opts.page));
|
|
684
|
+
if (opts.pageSize !== void 0) qs.set("pageSize", String(opts.pageSize));
|
|
685
|
+
if (opts.gender !== void 0) qs.set("gender", String(opts.gender));
|
|
686
|
+
const query = qs.toString();
|
|
687
|
+
return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
|
|
688
|
+
}
|
|
689
|
+
const SLOTS = 10;
|
|
690
|
+
function nonEmpty(value) {
|
|
691
|
+
return value !== void 0 && value !== null && String(value).trim() !== "";
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Per-set prescriptions from the param_N_data slots, e.g. ["5 @ 225", "3 @ 245"] or ["AMRAP"].
|
|
695
|
+
* Values are kept raw (a non-numeric prescription like "AMRAP" or "8-12" must survive); the
|
|
696
|
+
* positional units come from the exercise's param types, mirroring the coach presenter.
|
|
697
|
+
*/
|
|
698
|
+
function prescribedSets(ex) {
|
|
699
|
+
const out = [];
|
|
700
|
+
for (let i = 1; i <= SLOTS; i += 1) {
|
|
701
|
+
const p1 = ex[`param_1_data_${i}`];
|
|
702
|
+
const p2 = ex[`param_2_data_${i}`];
|
|
703
|
+
const has1 = nonEmpty(p1);
|
|
704
|
+
const has2 = nonEmpty(p2);
|
|
705
|
+
if (!has1 && !has2) continue;
|
|
706
|
+
if (has1 && has2) out.push(`${p1} @ ${p2}`);
|
|
707
|
+
else if (has1) out.push(String(p1));
|
|
708
|
+
else out.push(`@ ${p2}`);
|
|
709
|
+
}
|
|
710
|
+
return out;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* The per-set values the athlete actually logged, read from a saved-copy exercise. A set
|
|
714
|
+
* counts as performed only when its `param_{i}_made` flag is 1: the saved copy pre-fills the
|
|
715
|
+
* `param_N_data` slots with the prescription, so the presence of data alone does not mean a
|
|
716
|
+
* set was done. `param_{i}_made` is the same per-set flag the logging write sets, and is the
|
|
717
|
+
* only reliable signal (the `completed` flags are often left at 0 on a logged session).
|
|
718
|
+
*/
|
|
719
|
+
function performedSets(ex) {
|
|
720
|
+
const out = [];
|
|
721
|
+
for (let i = 1; i <= SLOTS; i += 1) {
|
|
722
|
+
if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
|
|
723
|
+
const p1 = ex[`param_1_data_${i}`];
|
|
724
|
+
const p2 = ex[`param_2_data_${i}`];
|
|
725
|
+
const has1 = nonEmpty(p1);
|
|
726
|
+
const has2 = nonEmpty(p2);
|
|
727
|
+
if (has1 && has2) out.push(`${p1} @ ${p2}`);
|
|
728
|
+
else if (has1) out.push(String(p1));
|
|
729
|
+
else if (has2) out.push(`@ ${p2}`);
|
|
730
|
+
}
|
|
731
|
+
return out;
|
|
732
|
+
}
|
|
733
|
+
function presentExercise(ex, performedById) {
|
|
734
|
+
const instruction = typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null;
|
|
735
|
+
const id = coerceInt(ex.id);
|
|
736
|
+
return {
|
|
737
|
+
exerciseId: coerceInt(ex.exercise_id),
|
|
738
|
+
title: typeof ex.title === "string" ? ex.title : "",
|
|
739
|
+
instruction,
|
|
740
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
741
|
+
prescribed: prescribedSets(ex),
|
|
742
|
+
performed: (id !== null ? performedById.get(id) : void 0) ?? []
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
function presentBlock(set, performedById) {
|
|
746
|
+
const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
|
|
747
|
+
return {
|
|
748
|
+
order: coerceInt(set.order) ?? 0,
|
|
749
|
+
title: typeof set.title === "string" && set.title !== "" ? set.title : null,
|
|
750
|
+
instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
|
|
751
|
+
isTest: coerceInt(set.is_test) === 1,
|
|
752
|
+
exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
function str$1(v) {
|
|
756
|
+
return typeof v === "string" && v !== "" ? v : null;
|
|
757
|
+
}
|
|
758
|
+
/** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
|
|
759
|
+
function savedSets(saved) {
|
|
760
|
+
const out = [];
|
|
761
|
+
for (const key of ["workoutSets", "addedWorkoutSets"]) {
|
|
762
|
+
const sets = Array.isArray(saved[key]) ? saved[key] : [];
|
|
763
|
+
for (const set of sets) {
|
|
764
|
+
if (!isRecord(set)) continue;
|
|
765
|
+
const exercises = (Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : []).filter(isRecord);
|
|
766
|
+
out.push({
|
|
767
|
+
set,
|
|
768
|
+
exercises
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return out;
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Map each prescription exercise id to the per-set values the athlete logged. In the saved
|
|
776
|
+
* copy, `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
|
|
777
|
+
* entered values live in the same `param_N_data` slots as a prescription — so the
|
|
778
|
+
* prescription reader works on them unchanged.
|
|
779
|
+
*/
|
|
780
|
+
function performedByExerciseId(sets) {
|
|
781
|
+
const map = /* @__PURE__ */ new Map();
|
|
782
|
+
for (const { exercises } of sets) for (const ex of exercises) {
|
|
783
|
+
const id = coerceInt(ex.workout_set_exercise_id);
|
|
784
|
+
if (id === null) continue;
|
|
785
|
+
const values = performedSets(ex);
|
|
786
|
+
if (values.length > 0) map.set(id, values);
|
|
787
|
+
}
|
|
788
|
+
return map;
|
|
789
|
+
}
|
|
790
|
+
/** Present a logged set straight from the saved copy (athlete-added or personal work). */
|
|
791
|
+
function presentSavedBlock(set, exercises) {
|
|
792
|
+
return {
|
|
793
|
+
order: coerceInt(set.order) ?? 0,
|
|
794
|
+
title: typeof set.title === "string" && set.title !== "" ? set.title : null,
|
|
795
|
+
instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
|
|
796
|
+
isTest: coerceInt(set.is_test) === 1,
|
|
797
|
+
exercises: exercises.map((ex) => ({
|
|
798
|
+
exerciseId: coerceInt(ex.exercise_id),
|
|
799
|
+
title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
|
|
800
|
+
instruction: typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null,
|
|
801
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
802
|
+
prescribed: [],
|
|
803
|
+
performed: performedSets(ex)
|
|
804
|
+
}))
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Flatten one `/3.0/athlete/programworkout/range` item into a readable workout, merging the
|
|
809
|
+
* prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
|
|
810
|
+
* (`summarizedSavedWorkout.saved_workout`). Each exercise carries both its `prescribed` and
|
|
811
|
+
* `performed` sets; athlete-added/personal work that has no prescription is appended as its
|
|
812
|
+
* own blocks. No `raw` is needed to see logged results.
|
|
813
|
+
*/
|
|
814
|
+
function presentAthleteWorkout(raw) {
|
|
815
|
+
const rec = raw;
|
|
816
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
817
|
+
const workout = isRecord(ssw.workout) ? ssw.workout : {};
|
|
818
|
+
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : {};
|
|
819
|
+
const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
|
|
820
|
+
const logged = savedSets(saved);
|
|
821
|
+
const performedById = performedByExerciseId(logged);
|
|
822
|
+
const blocks = prescriptionSets.map((s) => presentBlock(s, performedById)).sort((a, b) => a.order - b.order);
|
|
823
|
+
const prescribedIds = /* @__PURE__ */ new Set();
|
|
824
|
+
for (const s of prescriptionSets) {
|
|
825
|
+
const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
826
|
+
for (const ex of exs) {
|
|
827
|
+
if (!isRecord(ex)) continue;
|
|
828
|
+
const id = coerceInt(ex.id);
|
|
829
|
+
if (id !== null) prescribedIds.add(id);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
for (const { set, exercises } of logged) {
|
|
833
|
+
const extra = exercises.filter((ex) => {
|
|
834
|
+
if (performedSets(ex).length === 0) return false;
|
|
835
|
+
const id = coerceInt(ex.workout_set_exercise_id);
|
|
836
|
+
return id === null || !prescribedIds.has(id);
|
|
837
|
+
});
|
|
838
|
+
if (extra.length > 0) blocks.push(presentSavedBlock(set, extra));
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
id: coerceInt(rec.id),
|
|
842
|
+
date: str$1(rec.date) ?? "",
|
|
843
|
+
title: str$1(rec.workout_title) ?? "",
|
|
844
|
+
program: str$1(rec.program_title),
|
|
845
|
+
team: str$1(rec.team_title),
|
|
846
|
+
instruction: str$1(workout.instruction),
|
|
847
|
+
logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
|
|
848
|
+
blocks
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
function presentAthleteWorkouts(list) {
|
|
852
|
+
return list.map(presentAthleteWorkout);
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
|
|
856
|
+
* location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
|
|
857
|
+
* This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
|
|
858
|
+
* which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
|
|
859
|
+
* `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
|
|
860
|
+
* with no resolvable id.
|
|
861
|
+
*/
|
|
862
|
+
function presentLogTargets(list) {
|
|
863
|
+
const targets = [];
|
|
864
|
+
for (const pw of list) {
|
|
865
|
+
const rec = pw;
|
|
866
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
867
|
+
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
868
|
+
if (!saved) continue;
|
|
869
|
+
const date = str$1(rec.date) ?? "";
|
|
870
|
+
const workoutTitle = str$1(rec.workout_title) ?? "";
|
|
871
|
+
const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
|
|
872
|
+
for (const s of sets) {
|
|
873
|
+
if (!isRecord(s)) continue;
|
|
874
|
+
const savedWorkoutSetId = coerceInt(s.id);
|
|
875
|
+
if (savedWorkoutSetId === null) continue;
|
|
876
|
+
const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
|
|
877
|
+
const id = coerceInt(ex.id);
|
|
878
|
+
if (id === null) return null;
|
|
879
|
+
return {
|
|
880
|
+
savedWorkoutSetExerciseId: id,
|
|
881
|
+
title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
|
|
882
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
883
|
+
prescribed: prescribedSets(ex),
|
|
884
|
+
performed: performedSets(ex)
|
|
885
|
+
};
|
|
886
|
+
}).filter((e) => e !== null);
|
|
887
|
+
targets.push({
|
|
888
|
+
date,
|
|
889
|
+
workoutTitle,
|
|
890
|
+
savedWorkoutSetId,
|
|
891
|
+
setTitle: str$1(s.title),
|
|
892
|
+
exercises
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return targets;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
|
|
900
|
+
* keeps only workouts the athlete logged a set on (the reliable signal, not the API's
|
|
901
|
+
* completion flag). `limit` keeps the most recent N by date (newest first). Both are pure
|
|
902
|
+
* post-filters over the presented view; the raw API path is left untouched.
|
|
903
|
+
*/
|
|
904
|
+
function selectWorkouts(list, opts = {}) {
|
|
905
|
+
let out = opts.loggedOnly === true ? list.filter((w) => w.logged) : [...list];
|
|
906
|
+
if (opts.limit !== void 0) out = [...out].sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : 0).slice(0, opts.limit);
|
|
907
|
+
return out;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Project presented workouts to compact headers (date/title/program + logged flag + exercise
|
|
911
|
+
* counts), dropping the per-set block detail. A dense multi-program week of full views can be
|
|
912
|
+
* tens of KB; this keeps an overview question to one small row per session, with a drill-in
|
|
913
|
+
* (narrow the date range) when the detail is actually needed.
|
|
914
|
+
*/
|
|
915
|
+
function summarizeAthleteWorkouts(list) {
|
|
916
|
+
return list.map((w) => {
|
|
917
|
+
const exerciseCount = w.blocks.reduce((n, b) => n + b.exercises.length, 0);
|
|
918
|
+
const performedCount = w.blocks.reduce((n, b) => n + b.exercises.filter((e) => e.performed.length > 0).length, 0);
|
|
919
|
+
return {
|
|
920
|
+
id: w.id,
|
|
921
|
+
date: w.date,
|
|
922
|
+
title: w.title,
|
|
923
|
+
program: w.program,
|
|
924
|
+
team: w.team,
|
|
925
|
+
logged: w.logged,
|
|
926
|
+
exerciseCount,
|
|
927
|
+
performedCount
|
|
928
|
+
};
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
|
|
933
|
+
* flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
|
|
934
|
+
* the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
|
|
935
|
+
* the discovery handle a coach otherwise lacks: read what the athlete actually did, then pull the
|
|
936
|
+
* specific lift's PRs.
|
|
937
|
+
*/
|
|
938
|
+
function presentCoachAthleteTraining(raw, athleteId, year, month) {
|
|
939
|
+
const sessions = [];
|
|
940
|
+
let athleteName = null;
|
|
941
|
+
for (const item of raw) {
|
|
942
|
+
if (!isRecord(item)) continue;
|
|
943
|
+
if (athleteName === null && typeof item.athleteName === "string") athleteName = item.athleteName;
|
|
944
|
+
const exercises = [];
|
|
945
|
+
const sets = Array.isArray(item.sets) ? item.sets : [];
|
|
946
|
+
for (const set of sets) {
|
|
947
|
+
if (!isRecord(set)) continue;
|
|
948
|
+
const exs = Array.isArray(set.exercises) ? set.exercises : [];
|
|
949
|
+
for (const ex of exs) {
|
|
950
|
+
if (!isRecord(ex)) continue;
|
|
951
|
+
exercises.push({
|
|
952
|
+
exerciseId: coerceInt(ex.exercise_id),
|
|
953
|
+
title: typeof ex.title === "string" ? ex.title : "",
|
|
954
|
+
summary: typeof ex.abr === "string" && ex.abr !== "" ? ex.abr : null,
|
|
955
|
+
completed: coerceInt(ex.completed) === 1
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
sessions.push({
|
|
960
|
+
workoutId: coerceInt(item.workout_id),
|
|
961
|
+
savedWorkoutId: coerceInt(item.saved_workout_id),
|
|
962
|
+
title: typeof item.workout_title === "string" ? item.workout_title : "",
|
|
963
|
+
logged: coerceInt(item.logged) === 1,
|
|
964
|
+
completed: coerceInt(item.completed) === 1,
|
|
965
|
+
rpe: coerceInt(item.rpe),
|
|
966
|
+
durationMin: coerceInt(item.session_duration),
|
|
967
|
+
notes: typeof item.notes === "string" && item.notes !== "" ? item.notes : null,
|
|
968
|
+
exercises
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return {
|
|
972
|
+
athleteId,
|
|
973
|
+
athleteName,
|
|
974
|
+
year,
|
|
975
|
+
month,
|
|
976
|
+
sessions
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
const MAX_PARAM_SLOTS = 10;
|
|
980
|
+
/**
|
|
981
|
+
* Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
|
|
982
|
+
* snake_case keys matching the live API response shape. Each set slot (1-10) gets a
|
|
983
|
+
* `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
|
|
984
|
+
* `param_2_data_N` string values.
|
|
985
|
+
*
|
|
986
|
+
* Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
|
|
987
|
+
* required from the live exercise record; everything else is derived from `results`.
|
|
988
|
+
*
|
|
989
|
+
* Exported for unit testing — callers should use `logAthleteSet` instead.
|
|
990
|
+
*/
|
|
991
|
+
function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
|
|
992
|
+
if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
|
|
993
|
+
const body = {
|
|
994
|
+
id: savedWorkoutSetExerciseId,
|
|
995
|
+
saved_workout_set_id: savedWorkoutSetId,
|
|
996
|
+
workout_set_exercise_id: workoutSetExerciseId,
|
|
997
|
+
completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
|
|
998
|
+
};
|
|
999
|
+
for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
|
|
1000
|
+
const slot = results[i - 1];
|
|
1001
|
+
const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
|
|
1002
|
+
const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
|
|
1003
|
+
body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
|
|
1004
|
+
body[`param_1_data_${i}`] = p1;
|
|
1005
|
+
body[`param_2_data_${i}`] = p2;
|
|
1006
|
+
}
|
|
1007
|
+
return body;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Locate the target saved workout set across all program workouts on the given day.
|
|
1011
|
+
* Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
|
|
1012
|
+
* can look up `workout_set_exercise_id` by `savedWorkoutSetExerciseId`, and the raw set
|
|
1013
|
+
* record so callers can build the set-completion PUT body via `buildSetCompletePayload`.
|
|
1014
|
+
*/
|
|
1015
|
+
function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
|
|
1016
|
+
const available = [];
|
|
1017
|
+
for (const pw of workouts) {
|
|
1018
|
+
const rec = pw;
|
|
1019
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1020
|
+
const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
1021
|
+
if (!sw) continue;
|
|
1022
|
+
const sets = Array.isArray(sw.workoutSets) ? sw.workoutSets : [];
|
|
1023
|
+
for (const s of sets) {
|
|
1024
|
+
if (!isRecord(s)) continue;
|
|
1025
|
+
const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [];
|
|
1026
|
+
if (coerceInt(s.id) === savedWorkoutSetId) {
|
|
1027
|
+
const savedWorkoutId = coerceInt(sw.id);
|
|
1028
|
+
if (!savedWorkoutId) continue;
|
|
1029
|
+
return {
|
|
1030
|
+
savedWorkoutId,
|
|
1031
|
+
exercises,
|
|
1032
|
+
rawSet: s
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
const setId = coerceInt(s.id);
|
|
1036
|
+
if (setId !== null) {
|
|
1037
|
+
const exLabels = exercises.map((ex) => {
|
|
1038
|
+
const exId = coerceInt(ex.id);
|
|
1039
|
+
const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
|
|
1040
|
+
return exId === null ? null : `${exId} (${title})`;
|
|
1041
|
+
}).filter((x) => x !== null);
|
|
1042
|
+
available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
const hint = available.length > 0 ? ` Saved workout sets present on this date: ${available.join("; ")}. Pass a "set N" id to --set (the savedWorkoutSetId), and the matching "exercise id" as savedWorkoutSetExerciseId in the results.` : " No saved workout is scheduled on this date — log against a date that has a workout (find it via athlete-workouts / coach athlete-workouts).";
|
|
1047
|
+
throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.${hint}`);
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Build the body for `PUT /1.0/athlete/savedworkoutset/{id}` that marks the set completed.
|
|
1051
|
+
*
|
|
1052
|
+
* The API requires the **app's camelCase in-memory model**, not the snake_case shape the
|
|
1053
|
+
* GET endpoints return. Key field mappings from the raw set record:
|
|
1054
|
+
* saved_workout_id → sessionId
|
|
1055
|
+
* workout_set_id → workoutSetId
|
|
1056
|
+
* is_super_set (0/1) → isSuperSet (boolean)
|
|
1057
|
+
* plain_text (0/1) → isPlainText (boolean)
|
|
1058
|
+
* unit ("lb"/"kg") → isMetric (boolean)
|
|
1059
|
+
* workoutSetExercises[].id → exercises (array of IDs)
|
|
1060
|
+
*
|
|
1061
|
+
* `exerciseIds` must be the savedWorkoutSetExercise IDs (not workout_set_exercise_ids).
|
|
1062
|
+
*
|
|
1063
|
+
* Exported for unit testing — callers should use `logAthleteSet` instead.
|
|
1064
|
+
*/
|
|
1065
|
+
function buildSetCompletePayload(rawSet, exerciseIds, complete) {
|
|
1066
|
+
const id = coerceInt(rawSet.id);
|
|
1067
|
+
const sessionId = coerceInt(rawSet.saved_workout_id);
|
|
1068
|
+
const workoutSetId = coerceInt(rawSet.workout_set_id);
|
|
1069
|
+
if (!id || !sessionId || !workoutSetId) throw new Error("Raw set is missing required id / saved_workout_id / workout_set_id.");
|
|
1070
|
+
const unit = typeof rawSet.unit === "string" ? rawSet.unit : "";
|
|
1071
|
+
return {
|
|
1072
|
+
id,
|
|
1073
|
+
sessionId,
|
|
1074
|
+
workoutSetId,
|
|
1075
|
+
completed: complete ? "1" : "0",
|
|
1076
|
+
rx: coerceInt(rawSet.rx) ?? 0,
|
|
1077
|
+
version: coerceInt(rawSet.version) ?? 0,
|
|
1078
|
+
isMetric: unit.toLowerCase() === "kg",
|
|
1079
|
+
isSuperSet: rawSet.is_super_set === 1 || rawSet.is_super_set === true,
|
|
1080
|
+
isPlainText: rawSet.plain_text === 1 || rawSet.plain_text === true,
|
|
1081
|
+
title: typeof rawSet.title === "string" ? rawSet.title : "",
|
|
1082
|
+
instruction: typeof rawSet.instruction === "string" ? rawSet.instruction : "",
|
|
1083
|
+
notes: rawSet.notes ?? null,
|
|
1084
|
+
exercises: [...exerciseIds]
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
* Record entered set results for one saved workout set.
|
|
1089
|
+
*
|
|
1090
|
+
* **Two-step write (both required for data to persist):**
|
|
1091
|
+
* 1. For each exercise in `results`:
|
|
1092
|
+
* `PUT /1.0/athlete/savedworkoutsetexercise/{savedWorkoutSetExerciseId}` with the
|
|
1093
|
+
* per-slot `param_N_data_M` values. This is the only path that actually stores reps
|
|
1094
|
+
* and weight — the `savedworkoutset` PUT accepts the same fields but silently discards
|
|
1095
|
+
* them.
|
|
1096
|
+
* 2. `PUT /1.0/athlete/savedworkoutset/{savedWorkoutSetId}` with `completed:"1"` to
|
|
1097
|
+
* mark the block done and make the entry visible as a logged set in history.
|
|
1098
|
+
*
|
|
1099
|
+
* The date is used to locate the saved workout (via the range endpoint) so we can resolve
|
|
1100
|
+
* `saved_workout_id` and `workout_set_exercise_id` for each exercise. Both are required
|
|
1101
|
+
* by the respective PUT bodies.
|
|
1102
|
+
*/
|
|
1103
|
+
async function logAthleteSet(client, args) {
|
|
1104
|
+
return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
|
|
1108
|
+
* coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
|
|
1109
|
+
* then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
|
|
1110
|
+
* contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
|
|
1111
|
+
* `athleteId`. The day is located through the coach range endpoint for that athlete.
|
|
1112
|
+
*
|
|
1113
|
+
* NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
|
|
1114
|
+
* data-write step; real (invited) athletes accept it.
|
|
1115
|
+
*/
|
|
1116
|
+
async function logForAthlete(client, args) {
|
|
1117
|
+
const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
|
|
1118
|
+
return writeSetResults(client, {
|
|
1119
|
+
role: "coach",
|
|
1120
|
+
athleteId: args.athleteId
|
|
1121
|
+
}, workouts, args.savedWorkoutSetId, args.results);
|
|
1122
|
+
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
|
|
1125
|
+
* `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
|
|
1126
|
+
* `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
|
|
1127
|
+
* exercise's entered data to its own endpoint (the only path that actually stores reps and
|
|
1128
|
+
* weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
|
|
1129
|
+
* shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
|
|
1130
|
+
*/
|
|
1131
|
+
async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
|
|
1132
|
+
const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
|
|
1133
|
+
const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
|
|
1134
|
+
const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
|
|
1135
|
+
let exercisesLogged = 0;
|
|
1136
|
+
for (const result of results) {
|
|
1137
|
+
const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
|
|
1138
|
+
if (!ex) {
|
|
1139
|
+
const valid = exercises.map((e) => {
|
|
1140
|
+
const id = coerceInt(e.id);
|
|
1141
|
+
const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
|
|
1142
|
+
return id === null ? null : `${id} (${title})`;
|
|
1143
|
+
}).filter((x) => x !== null);
|
|
1144
|
+
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
1145
|
+
}
|
|
1146
|
+
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
1147
|
+
if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
|
|
1148
|
+
const body = {
|
|
1149
|
+
...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
|
|
1150
|
+
...extra
|
|
1151
|
+
};
|
|
1152
|
+
const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
|
|
1153
|
+
if (!res.ok) {
|
|
1154
|
+
const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for results — TrainHeroic's seeded demo/sample athletes return ${res.status} here; results only persist for real (invited) athletes.` : "";
|
|
1155
|
+
throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
|
|
1156
|
+
}
|
|
1157
|
+
exercisesLogged += 1;
|
|
1158
|
+
}
|
|
1159
|
+
const setBody = {
|
|
1160
|
+
...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
|
|
1161
|
+
...extra
|
|
1162
|
+
};
|
|
1163
|
+
const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
|
|
1164
|
+
if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
|
|
1165
|
+
return {
|
|
1166
|
+
savedWorkoutSetId,
|
|
1167
|
+
exercisesLogged
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
1171
|
+
function presentExerciseHistory(detail) {
|
|
1172
|
+
return {
|
|
1173
|
+
liftPRs: (detail.liftPRs ?? []).map((p) => ({
|
|
1174
|
+
description: p.description ?? null,
|
|
1175
|
+
reps: p.reps ?? null,
|
|
1176
|
+
weight: p.weight ?? null,
|
|
1177
|
+
date: p.dateCompleted ?? null
|
|
1178
|
+
})),
|
|
1179
|
+
sessions: (detail.history ?? []).map((h) => ({
|
|
1180
|
+
date: h.dateCompleted,
|
|
1181
|
+
abr: h.abr ?? null,
|
|
1182
|
+
estimated1RM: h.bestEstimated1RM ?? null,
|
|
1183
|
+
sets: (h.sets ?? []).map((s) => ({
|
|
1184
|
+
setNumber: s.setNumber,
|
|
1185
|
+
value: s.formattedValue ?? null
|
|
1186
|
+
}))
|
|
1187
|
+
}))
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
/** Normalize one-or-many emails into a deduped, trimmed list. */
|
|
1191
|
+
function emailList(emails) {
|
|
1192
|
+
return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
1193
|
+
}
|
|
1194
|
+
/**
|
|
1195
|
+
* Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
|
|
1196
|
+
* addresses (`POST /v5/emails/validate`), then invite the validated ones
|
|
1197
|
+
* (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
|
|
1198
|
+
*/
|
|
1199
|
+
async function inviteAthletes(client, args) {
|
|
1200
|
+
const list = emailList(args.emails);
|
|
1201
|
+
if (list.length === 0) throw new Error("Provide at least one email address to invite.");
|
|
1202
|
+
const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
|
|
1203
|
+
if (!validation.ok) {
|
|
1204
|
+
const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
|
|
1205
|
+
throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
|
|
1206
|
+
}
|
|
1207
|
+
const valid = Array.isArray(validation.data) ? validation.data : list;
|
|
1208
|
+
if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
|
|
1209
|
+
const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
|
|
1210
|
+
teamType: 0,
|
|
1211
|
+
teamId: args.teamId,
|
|
1212
|
+
orgId: null,
|
|
1213
|
+
emails: valid,
|
|
1214
|
+
message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
|
|
1215
|
+
} });
|
|
1216
|
+
if (!invite.ok) {
|
|
1217
|
+
const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
|
|
1218
|
+
throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
|
|
1219
|
+
}
|
|
1220
|
+
return {
|
|
1221
|
+
teamId: args.teamId,
|
|
1222
|
+
invited: valid,
|
|
1223
|
+
result: invite.data
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
|
|
1228
|
+
* The API wants the target date as a structured object (with weekday and an isToday flag),
|
|
1229
|
+
* which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
|
|
1230
|
+
*/
|
|
1231
|
+
async function copySession(client, args) {
|
|
1232
|
+
const [year, month, day] = parseWorkoutDate(args.toDate);
|
|
1233
|
+
const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
|
|
1234
|
+
const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
|
|
1235
|
+
const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
|
|
1236
|
+
toProgramId: args.toProgramId,
|
|
1237
|
+
pwId: args.pwId,
|
|
1238
|
+
toDate: {
|
|
1239
|
+
date: iso,
|
|
1240
|
+
day,
|
|
1241
|
+
month,
|
|
1242
|
+
year,
|
|
1243
|
+
dayOfWeek,
|
|
1244
|
+
isToday: false
|
|
1245
|
+
}
|
|
1246
|
+
} });
|
|
1247
|
+
if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
|
|
1248
|
+
return res.data;
|
|
1249
|
+
}
|
|
1250
|
+
const ANALYTICS_METRIC_KEYS = [
|
|
1251
|
+
"readiness-team",
|
|
1252
|
+
"readiness-athlete",
|
|
1253
|
+
"lift-1rm-history",
|
|
1254
|
+
"training-summary-athlete",
|
|
1255
|
+
"compliance-team",
|
|
1256
|
+
"lift-progress-team",
|
|
1257
|
+
"working-max-history"
|
|
1258
|
+
];
|
|
1259
|
+
const ANALYTICS_METRICS = {
|
|
1260
|
+
"readiness-team": {
|
|
1261
|
+
path: "/v5/analytics/readiness/teams",
|
|
1262
|
+
scope: "team",
|
|
1263
|
+
inputs: ["date"],
|
|
1264
|
+
requires: ["date"]
|
|
1265
|
+
},
|
|
1266
|
+
"readiness-athlete": {
|
|
1267
|
+
path: "/v5/analytics/readiness/users",
|
|
1268
|
+
scope: "user",
|
|
1269
|
+
inputs: ["dateStart", "dateEnd"],
|
|
1270
|
+
requires: ["dateStart", "dateEnd"]
|
|
1271
|
+
},
|
|
1272
|
+
"lift-1rm-history": {
|
|
1273
|
+
path: "/v5/analytics/lift-one-rep-max-history/users",
|
|
1274
|
+
scope: "user",
|
|
1275
|
+
inputs: [
|
|
1276
|
+
"dateStart",
|
|
1277
|
+
"dateEnd",
|
|
1278
|
+
"exerciseId",
|
|
1279
|
+
"useMetric"
|
|
1280
|
+
],
|
|
1281
|
+
requires: [
|
|
1282
|
+
"dateStart",
|
|
1283
|
+
"dateEnd",
|
|
1284
|
+
"exerciseId"
|
|
1285
|
+
]
|
|
1286
|
+
},
|
|
1287
|
+
"training-summary-athlete": {
|
|
1288
|
+
path: "/v5/analytics/training-summary/users",
|
|
1289
|
+
scope: "user",
|
|
1290
|
+
inputs: ["dateStart", "dateEnd"],
|
|
1291
|
+
requires: ["dateStart", "dateEnd"]
|
|
1292
|
+
},
|
|
1293
|
+
"compliance-team": {
|
|
1294
|
+
path: "/v5/analytics/compliance",
|
|
1295
|
+
scope: "team",
|
|
1296
|
+
inputs: ["dateStart", "dateEnd"],
|
|
1297
|
+
requires: ["dateStart", "dateEnd"]
|
|
1298
|
+
},
|
|
1299
|
+
"lift-progress-team": {
|
|
1300
|
+
path: "/v5/analytics/lift-progress/teams",
|
|
1301
|
+
scope: "team",
|
|
1302
|
+
inputs: [
|
|
1303
|
+
"exerciseId",
|
|
1304
|
+
"dateStart",
|
|
1305
|
+
"dateEnd"
|
|
1306
|
+
],
|
|
1307
|
+
requires: [
|
|
1308
|
+
"exerciseId",
|
|
1309
|
+
"dateStart",
|
|
1310
|
+
"dateEnd"
|
|
1311
|
+
]
|
|
1312
|
+
},
|
|
1313
|
+
"working-max-history": {
|
|
1314
|
+
path: "/v5/analytics/working-max-history/users",
|
|
1315
|
+
scope: "user",
|
|
1316
|
+
inputs: [
|
|
1317
|
+
"exerciseId",
|
|
1318
|
+
"dateStart",
|
|
1319
|
+
"dateEnd",
|
|
1320
|
+
"useMetric"
|
|
1321
|
+
],
|
|
1322
|
+
requires: ["exerciseId"]
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
/**
|
|
1326
|
+
* A serializable description of every analytics metric: its scope (does it need a `teamId` or
|
|
1327
|
+
* `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
|
|
1328
|
+
* surface this so an agent picks a valid `metric` + params up front, instead of discovering the
|
|
1329
|
+
* shape by trial and error. These curated keys are deliberately NOT the raw category names from
|
|
1330
|
+
* `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
|
|
1331
|
+
*/
|
|
1332
|
+
function analyticsMetricCatalog() {
|
|
1333
|
+
return ANALYTICS_METRIC_KEYS.map((metric) => {
|
|
1334
|
+
const spec = ANALYTICS_METRICS[metric];
|
|
1335
|
+
return {
|
|
1336
|
+
metric,
|
|
1337
|
+
scope: spec.scope,
|
|
1338
|
+
scopeParam: spec.scope === "team" ? "teamId" : "userIds",
|
|
1339
|
+
requires: [...spec.requires],
|
|
1340
|
+
optional: spec.inputs.filter((i) => !spec.requires.includes(i))
|
|
1341
|
+
};
|
|
1342
|
+
});
|
|
1343
|
+
}
|
|
1344
|
+
const ANALYTICS_BODY_KEY = {
|
|
1345
|
+
date: "date",
|
|
1346
|
+
dateStart: "date_start",
|
|
1347
|
+
dateEnd: "date_end",
|
|
1348
|
+
exerciseId: "exercise_id",
|
|
1349
|
+
useMetric: "use_metric"
|
|
1350
|
+
};
|
|
1351
|
+
/**
|
|
1352
|
+
* Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
|
|
1353
|
+
* athlete metrics need one or more `userIds` (passed together — the report returns a row per
|
|
1354
|
+
* athlete). Throws a readable Error when a required input is missing or the call fails.
|
|
1355
|
+
*/
|
|
1356
|
+
async function queryAnalytics(client, args) {
|
|
1357
|
+
const spec = ANALYTICS_METRICS[args.metric];
|
|
1358
|
+
const body = {};
|
|
1359
|
+
if (spec.scope === "team") {
|
|
1360
|
+
if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
|
|
1361
|
+
body.teamId = args.teamId;
|
|
1362
|
+
} else {
|
|
1363
|
+
if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
|
|
1364
|
+
body.user_ids = args.userIds.map((u) => String(u));
|
|
1365
|
+
}
|
|
1366
|
+
const inputs = {
|
|
1367
|
+
date: args.date,
|
|
1368
|
+
dateStart: args.dateStart,
|
|
1369
|
+
dateEnd: args.dateEnd,
|
|
1370
|
+
exerciseId: args.exerciseId,
|
|
1371
|
+
useMetric: args.useMetric
|
|
1372
|
+
};
|
|
1373
|
+
const missing = spec.requires.filter((k) => inputs[k] === void 0);
|
|
1374
|
+
if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
|
|
1375
|
+
for (const k of spec.inputs) {
|
|
1376
|
+
const v = inputs[k];
|
|
1377
|
+
if (v === void 0) continue;
|
|
1378
|
+
body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
|
|
1379
|
+
}
|
|
1380
|
+
const res = await client.request("POST", spec.path, { body });
|
|
1381
|
+
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
1382
|
+
return res.data;
|
|
1383
|
+
}
|
|
1384
|
+
//#endregion
|
|
1385
|
+
//#region ../js/src/util.ts
|
|
1386
|
+
/**
|
|
1387
|
+
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
1388
|
+
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
1389
|
+
* `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
|
|
1390
|
+
* optional ones lose `undefined` from their value type.
|
|
1391
|
+
*
|
|
1392
|
+
* Example:
|
|
1393
|
+
* definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
|
|
1394
|
+
*/
|
|
1395
|
+
function definedProps(obj) {
|
|
1396
|
+
const result = {};
|
|
1397
|
+
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
|
|
1398
|
+
return result;
|
|
1399
|
+
}
|
|
347
1400
|
//#endregion
|
|
348
1401
|
//#region ../js/src/workout-encode.ts
|
|
349
1402
|
const LEADERBOARD_TYPE = {
|
|
@@ -831,10 +1884,7 @@ var ExerciseLibrary = class {
|
|
|
831
1884
|
await this.ensureFresh();
|
|
832
1885
|
const s = this.#byId.get(id);
|
|
833
1886
|
if (!s) return null;
|
|
834
|
-
|
|
835
|
-
full.param_1_unit = unitLabel(full.param_1_type);
|
|
836
|
-
full.param_2_unit = unitLabel(full.param_2_type);
|
|
837
|
-
return full;
|
|
1887
|
+
return presentExercise$1(s.raw);
|
|
838
1888
|
}
|
|
839
1889
|
async defaults(id) {
|
|
840
1890
|
const s = this.#byId.get(id);
|
|
@@ -970,33 +2020,90 @@ async function saveSession(sessionId) {
|
|
|
970
2020
|
const HELP = `trainheroic — command-line tool for the TrainHeroic coaching API
|
|
971
2021
|
|
|
972
2022
|
Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
|
|
2023
|
+
Coaching commands live under 'coach'; your own training lives under 'athlete'.
|
|
2024
|
+
|
|
2025
|
+
Start here (for AI agents):
|
|
2026
|
+
trainheroic skill full workflow guide + copy-paste examples (esp. workout specs)
|
|
2027
|
+
trainheroic skill --full also print the API + workout-creation reference docs
|
|
2028
|
+
trainheroic skill list list the available guides (coach, athlete)
|
|
2029
|
+
|
|
2030
|
+
Setup:
|
|
2031
|
+
install-skill copy the Claude Code skills to ~/.claude/skills/
|
|
2032
|
+
|
|
2033
|
+
Shared:
|
|
2034
|
+
whoami the logged-in account
|
|
2035
|
+
request <METHOD> <path> [json] [--base coach|apis] [--file f] raw API call (--base defaults to coach)
|
|
973
2036
|
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
program <id> | team <id> | team-codes <id>
|
|
977
|
-
request <METHOD> <path> [json] [--base coach|apis] [--file f] raw API call
|
|
2037
|
+
Coach — manage a roster (needs a coach account):
|
|
2038
|
+
coach head-coach | athletes | programs | teams | notifications | analytics
|
|
2039
|
+
coach program <id> | team <id> | team-codes <id>
|
|
978
2040
|
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
exercise
|
|
984
|
-
exercise create <json>|--file f
|
|
985
|
-
exercise forget <id> --yes
|
|
986
|
-
exercise stats
|
|
2041
|
+
roster athlete reads (three lenses — pick by the question):
|
|
2042
|
+
coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume (team-volume questions live HERE, not analytics-query). All-time snapshot, no date range. Get the full id list from 'coach athletes'.
|
|
2043
|
+
coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
|
|
2044
|
+
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)
|
|
2045
|
+
coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
|
|
987
2046
|
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
workout remove --program <id> --pw <id> --yes
|
|
2047
|
+
log for an athlete (record their reps/weights; real invited athletes only — demo/seeded ones 401):
|
|
2048
|
+
coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes
|
|
2049
|
+
--date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
|
|
2050
|
+
and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
|
|
993
2051
|
|
|
994
|
-
|
|
995
|
-
message
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
2052
|
+
roster management:
|
|
2053
|
+
coach athlete-invite --team <id> --emails a@x,b@y [--message "..."] --yes
|
|
2054
|
+
coach athlete-archive --athletes <id,id,...> --yes
|
|
2055
|
+
coach athlete-restore --athletes <id,id,...>
|
|
2056
|
+
|
|
2057
|
+
teams & join codes:
|
|
2058
|
+
coach team-create --title "..."
|
|
2059
|
+
coach team-update --team <id> --title "..."
|
|
2060
|
+
coach team-delete --team <id> --yes
|
|
2061
|
+
coach team-code-create --team <id> [--type N]
|
|
2062
|
+
coach team-code-delete --code <id> --yes (--code is the id from team-code-create, not the join-code number)
|
|
2063
|
+
|
|
2064
|
+
session lifecycle:
|
|
2065
|
+
coach session-copy --to-program <id> --pw <id> --to-date Y-M-D
|
|
2066
|
+
coach session-unpublish --pw <id> --yes
|
|
2067
|
+
coach session-save-template --workout <id>
|
|
2068
|
+
|
|
2069
|
+
analytics (curated metrics; for team training volume/recency use roster-activity --metric instead):
|
|
2070
|
+
coach analytics-query [--metric <key>] [--team <id>] [--users id,id] [--exercise <id>] [--date|--start|--end Y-M-D] [--use-metric]
|
|
2071
|
+
run with no --metric to list the valid keys + each one's scope and required params
|
|
2072
|
+
(these keys are curated and differ from the raw 'coach analytics' categories)
|
|
2073
|
+
|
|
2074
|
+
exercise library (cached at ~/.trainheroic/library.json):
|
|
2075
|
+
coach exercise resolve <name>
|
|
2076
|
+
coach exercise search <query> [--limit N]
|
|
2077
|
+
coach exercise get <id>
|
|
2078
|
+
coach exercise sync [--force]
|
|
2079
|
+
coach exercise create <json>|--file f
|
|
2080
|
+
coach exercise forget <id> --yes
|
|
2081
|
+
coach exercise stats
|
|
2082
|
+
|
|
2083
|
+
workouts (spec: {"blocks":[{"title","exercises":[{"id","sets"?,"reps"?,"weight"?,"rpe"?}]}],"instruction"?};
|
|
2084
|
+
reps/weight may be a scalar or per-set array; omit --publish to leave a draft):
|
|
2085
|
+
coach workout build --program <id> (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
|
|
2086
|
+
coach workout read --program <id> --date Y-M-D --pw <id>
|
|
2087
|
+
coach workout publish --pw <id> --yes
|
|
2088
|
+
coach workout remove --program <id> --pw <id> --yes
|
|
2089
|
+
|
|
2090
|
+
messaging:
|
|
2091
|
+
coach message list
|
|
2092
|
+
coach message read <streamId> [--limit N]
|
|
2093
|
+
coach message draft <streamId> <text> [--reply-to <id>]
|
|
2094
|
+
coach message send <streamId> <text> [--reply-to <id>] --yes
|
|
2095
|
+
coach message delete <streamId> <commentId> --yes
|
|
2096
|
+
|
|
2097
|
+
Athlete — the logged-in user's own training (a coach account works too):
|
|
2098
|
+
athlete whoami | profile [--metric] | prefs | working-maxes
|
|
2099
|
+
athlete workouts --start Y-M-D --end Y-M-D [--raw] [--log-ids] [--logged-only] [--limit N] [--summary] (--log-ids: the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs)
|
|
2100
|
+
athlete exercises [--q <text>] [--limit N]
|
|
2101
|
+
athlete history <exerciseId> [--raw]
|
|
2102
|
+
athlete prs <exerciseId>
|
|
2103
|
+
athlete stats <exerciseId> --date Y-M-D
|
|
2104
|
+
athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
|
|
2105
|
+
athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
|
|
2106
|
+
athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date — no ad-hoc sessions; ids from 'athlete workouts ... --log-ids')
|
|
1000
2107
|
`;
|
|
1001
2108
|
function out(value) {
|
|
1002
2109
|
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
|
@@ -1015,9 +2122,9 @@ function toInt(value, label) {
|
|
|
1015
2122
|
return n;
|
|
1016
2123
|
}
|
|
1017
2124
|
/** Validate input against a dto schema, failing with a readable message on mismatch. */
|
|
1018
|
-
function validate(schema, value, label) {
|
|
2125
|
+
function validate(schema, value, label, hint) {
|
|
1019
2126
|
const result = schema.safeParse(value);
|
|
1020
|
-
if (!result.success) fail(`invalid ${label} — ${result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
|
|
2127
|
+
if (!result.success) fail(`invalid ${label} — ${result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}${hint ? `\n${hint}` : ""}`);
|
|
1021
2128
|
return result.data;
|
|
1022
2129
|
}
|
|
1023
2130
|
function parse(args, options) {
|
|
@@ -1057,6 +2164,16 @@ async function get(client, path, base) {
|
|
|
1057
2164
|
if (!res.ok) fail(`GET ${path} failed (HTTP ${res.status}).`);
|
|
1058
2165
|
return res.data;
|
|
1059
2166
|
}
|
|
2167
|
+
/** A thin write request (POST/PUT/DELETE) that fails on a non-2xx and returns the body. */
|
|
2168
|
+
async function mutate(client, method, path, body) {
|
|
2169
|
+
const res = await client.request(method, path, body !== void 0 ? { body } : {});
|
|
2170
|
+
if (!res.ok) fail(`${method} ${path} failed (HTTP ${res.status}).`);
|
|
2171
|
+
return res.data;
|
|
2172
|
+
}
|
|
2173
|
+
/** Parse a comma-separated id list ("1,2,3") into numbers. */
|
|
2174
|
+
function idList(value, label) {
|
|
2175
|
+
return value.split(",").map((s) => toInt(s.trim(), label));
|
|
2176
|
+
}
|
|
1060
2177
|
function library(client) {
|
|
1061
2178
|
return new ExerciseLibrary(client, new JsonFileLibraryCache());
|
|
1062
2179
|
}
|
|
@@ -1085,14 +2202,14 @@ async function cmdExercise(client, rest) {
|
|
|
1085
2202
|
const [sub, ...a] = rest;
|
|
1086
2203
|
const lib = library(client);
|
|
1087
2204
|
switch (sub) {
|
|
1088
|
-
case "resolve": return out(await lib.resolve(need(a.join(" ").trim() || void 0, "exercise resolve <name>")));
|
|
2205
|
+
case "resolve": return out(await lib.resolve(need(a.join(" ").trim() || void 0, "coach exercise resolve <name>")));
|
|
1089
2206
|
case "search": {
|
|
1090
2207
|
const { values, positionals } = parse(a, { limit: { type: "string" } });
|
|
1091
|
-
const query = need(positionals.join(" ").trim() || void 0, "exercise search <query>");
|
|
2208
|
+
const query = need(positionals.join(" ").trim() || void 0, "coach exercise search <query>");
|
|
1092
2209
|
const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
|
|
1093
2210
|
return out(await lib.search(query, limit));
|
|
1094
2211
|
}
|
|
1095
|
-
case "get": return out(await lib.get(toInt(need(a[0], "exercise get <id>"), "id")));
|
|
2212
|
+
case "get": return out(await lib.get(toInt(need(a[0], "coach exercise get <id>"), "id")));
|
|
1096
2213
|
case "sync": {
|
|
1097
2214
|
const { values } = parse(a, { force: { type: "boolean" } });
|
|
1098
2215
|
if (values.force === true) return out(await lib.refresh());
|
|
@@ -1106,13 +2223,13 @@ async function cmdExercise(client, rest) {
|
|
|
1106
2223
|
}
|
|
1107
2224
|
case "forget": {
|
|
1108
2225
|
const { values, positionals } = parse(a, { yes: { type: "boolean" } });
|
|
1109
|
-
const id = toInt(need(positionals[0], "exercise forget <id> --yes"), "id");
|
|
2226
|
+
const id = toInt(need(positionals[0], "coach exercise forget <id> --yes"), "id");
|
|
1110
2227
|
if (values.yes !== true) fail(`add --yes to forget exercise ${id} from the local cache.`);
|
|
1111
2228
|
await lib.recordDelete(id);
|
|
1112
2229
|
return out({ forgotten: id });
|
|
1113
2230
|
}
|
|
1114
2231
|
case "stats": return out(await lib.stats());
|
|
1115
|
-
default: return fail("usage: trainheroic exercise <resolve|search|get|sync|create|forget|stats>");
|
|
2232
|
+
default: return fail("usage: trainheroic coach exercise <resolve|search|get|sync|create|forget|stats>");
|
|
1116
2233
|
}
|
|
1117
2234
|
}
|
|
1118
2235
|
async function cmdWorkout(client, rest) {
|
|
@@ -1127,10 +2244,10 @@ async function cmdWorkout(client, rest) {
|
|
|
1127
2244
|
yes: { type: "boolean" },
|
|
1128
2245
|
file: { type: "string" }
|
|
1129
2246
|
});
|
|
1130
|
-
const programId = toInt(need(values.program, "workout build --program <id> ..."), "--program");
|
|
2247
|
+
const programId = toInt(need(values.program, "coach workout build --program <id> ..."), "--program");
|
|
1131
2248
|
if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
|
|
1132
2249
|
const parsed = await jsonInput(positionals[0], values.file);
|
|
1133
|
-
const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec");
|
|
2250
|
+
const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
|
|
1134
2251
|
const publish = values.publish === true;
|
|
1135
2252
|
if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
|
|
1136
2253
|
const opts = {
|
|
@@ -1157,14 +2274,14 @@ async function cmdWorkout(client, rest) {
|
|
|
1157
2274
|
date: { type: "string" },
|
|
1158
2275
|
pw: { type: "string" }
|
|
1159
2276
|
});
|
|
1160
|
-
return out(await readSession(client, toInt(need(values.program, "workout read --program <id> --date Y-M-D --pw <id>"), "--program"), parseWorkoutDate(need(values.date, "workout read --program <id> --date Y-M-D --pw <id>")), toInt(need(values.pw, "workout read --program <id> --date Y-M-D --pw <id>"), "--pw")));
|
|
2277
|
+
return out(await readSession(client, toInt(need(values.program, "coach workout read --program <id> --date Y-M-D --pw <id>"), "--program"), parseWorkoutDate(need(values.date, "coach workout read --program <id> --date Y-M-D --pw <id>")), toInt(need(values.pw, "coach workout read --program <id> --date Y-M-D --pw <id>"), "--pw")));
|
|
1161
2278
|
}
|
|
1162
2279
|
case "publish": {
|
|
1163
2280
|
const { values } = parse(a, {
|
|
1164
2281
|
pw: { type: "string" },
|
|
1165
2282
|
yes: { type: "boolean" }
|
|
1166
2283
|
});
|
|
1167
|
-
const pw = toInt(need(values.pw, "workout publish --pw <id> --yes"), "--pw");
|
|
2284
|
+
const pw = toInt(need(values.pw, "coach workout publish --pw <id> --yes"), "--pw");
|
|
1168
2285
|
if (values.yes !== true) fail(`publishing makes pw ${pw} athlete-visible; add --yes.`);
|
|
1169
2286
|
await publishSession(client, pw);
|
|
1170
2287
|
return out({ published: pw });
|
|
@@ -1175,13 +2292,13 @@ async function cmdWorkout(client, rest) {
|
|
|
1175
2292
|
pw: { type: "string" },
|
|
1176
2293
|
yes: { type: "boolean" }
|
|
1177
2294
|
});
|
|
1178
|
-
const programId = toInt(need(values.program, "workout remove --program <id> --pw <id> --yes"), "--program");
|
|
1179
|
-
const pw = toInt(need(values.pw, "workout remove --program <id> --pw <id> --yes"), "--pw");
|
|
2295
|
+
const programId = toInt(need(values.program, "coach workout remove --program <id> --pw <id> --yes"), "--program");
|
|
2296
|
+
const pw = toInt(need(values.pw, "coach workout remove --program <id> --pw <id> --yes"), "--pw");
|
|
1180
2297
|
if (values.yes !== true) fail(`removing pw ${pw} deletes the session; add --yes.`);
|
|
1181
2298
|
await removeSession(client, programId, pw);
|
|
1182
2299
|
return out({ removed: pw });
|
|
1183
2300
|
}
|
|
1184
|
-
default: return fail("usage: trainheroic workout <build|read|publish|remove>");
|
|
2301
|
+
default: return fail("usage: trainheroic coach workout <build|read|publish|remove>");
|
|
1185
2302
|
}
|
|
1186
2303
|
}
|
|
1187
2304
|
async function cmdMessage(client, rest) {
|
|
@@ -1196,14 +2313,14 @@ async function cmdMessage(client, rest) {
|
|
|
1196
2313
|
})));
|
|
1197
2314
|
case "read": {
|
|
1198
2315
|
const { values, positionals } = parse(a, { limit: { type: "string" } });
|
|
1199
|
-
return out(await readLive(client, toInt(need(positionals[0], "message read <streamId> [--limit N]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20));
|
|
2316
|
+
return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20));
|
|
1200
2317
|
}
|
|
1201
2318
|
case "draft": {
|
|
1202
2319
|
const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
|
|
1203
2320
|
return out({
|
|
1204
2321
|
draft: true,
|
|
1205
2322
|
note: "NOT sent. Run 'message send' with --yes to deliver.",
|
|
1206
|
-
payload: buildCommentPayload(toInt(need(positionals[0], "message draft <streamId> <text>"), "streamId"), need(positionals.slice(1).join(" ").trim() || void 0, "message draft <streamId> <text>"), values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null)
|
|
2323
|
+
payload: buildCommentPayload(toInt(need(positionals[0], "coach message draft <streamId> <text>"), "streamId"), need(positionals.slice(1).join(" ").trim() || void 0, "coach message draft <streamId> <text>"), values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null)
|
|
1207
2324
|
});
|
|
1208
2325
|
}
|
|
1209
2326
|
case "send": {
|
|
@@ -1211,8 +2328,8 @@ async function cmdMessage(client, rest) {
|
|
|
1211
2328
|
"reply-to": { type: "string" },
|
|
1212
2329
|
yes: { type: "boolean" }
|
|
1213
2330
|
});
|
|
1214
|
-
const streamId = toInt(need(positionals[0], "message send <streamId> <text> --yes"), "streamId");
|
|
1215
|
-
const text = need(positionals.slice(1).join(" ").trim() || void 0, "message send <streamId> <text> --yes");
|
|
2331
|
+
const streamId = toInt(need(positionals[0], "coach message send <streamId> <text> --yes"), "streamId");
|
|
2332
|
+
const text = need(positionals.slice(1).join(" ").trim() || void 0, "coach message send <streamId> <text> --yes");
|
|
1216
2333
|
const replyTo = values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null;
|
|
1217
2334
|
if (values.yes !== true) fail(`sending to stream ${streamId} is athlete-facing and immediate; add --yes.`);
|
|
1218
2335
|
return out({
|
|
@@ -1222,33 +2339,508 @@ async function cmdMessage(client, rest) {
|
|
|
1222
2339
|
}
|
|
1223
2340
|
case "delete": {
|
|
1224
2341
|
const { values, positionals } = parse(a, { yes: { type: "boolean" } });
|
|
1225
|
-
const streamId = toInt(need(positionals[0], "message delete <streamId> <commentId> --yes"), "streamId");
|
|
1226
|
-
const commentId = toInt(need(positionals[1], "message delete <streamId> <commentId> --yes"), "commentId");
|
|
2342
|
+
const streamId = toInt(need(positionals[0], "coach message delete <streamId> <commentId> --yes"), "streamId");
|
|
2343
|
+
const commentId = toInt(need(positionals[1], "coach message delete <streamId> <commentId> --yes"), "commentId");
|
|
1227
2344
|
if (values.yes !== true) fail(`deleting comment ${commentId} acts on the live account; add --yes.`);
|
|
1228
2345
|
return out({
|
|
1229
2346
|
deleted: true,
|
|
1230
2347
|
response: await deleteComment(client, streamId, commentId)
|
|
1231
2348
|
});
|
|
1232
2349
|
}
|
|
1233
|
-
default: return fail("usage: trainheroic message <list|read|draft|send|delete>");
|
|
2350
|
+
default: return fail("usage: trainheroic coach message <list|read|draft|send|delete>");
|
|
1234
2351
|
}
|
|
1235
2352
|
}
|
|
1236
|
-
|
|
1237
|
-
|
|
2353
|
+
function isoDate(value, label) {
|
|
2354
|
+
if (!/^\d{4}-\d{2}-\d{2}$/u.test(value)) fail(`${label} must be YYYY-MM-DD, got "${value}".`);
|
|
2355
|
+
return value;
|
|
2356
|
+
}
|
|
2357
|
+
function logErr(msg) {
|
|
2358
|
+
process.stderr.write(`${msg}\n`);
|
|
2359
|
+
}
|
|
2360
|
+
async function cmdAthleteExport(client, a) {
|
|
2361
|
+
const { values } = parse(a, {
|
|
2362
|
+
out: { type: "string" },
|
|
2363
|
+
start: { type: "string" },
|
|
2364
|
+
end: { type: "string" },
|
|
2365
|
+
full: { type: "boolean" }
|
|
2366
|
+
});
|
|
2367
|
+
const dir = values.out ?? join(homedir(), ".trainheroic", "athlete-export");
|
|
2368
|
+
const today = /* @__PURE__ */ new Date();
|
|
2369
|
+
const past = /* @__PURE__ */ new Date();
|
|
2370
|
+
past.setFullYear(past.getFullYear() - 2);
|
|
2371
|
+
const start = values.start !== void 0 ? isoDate(values.start, "--start") : past.toISOString().slice(0, 10);
|
|
2372
|
+
const end = values.end !== void 0 ? isoDate(values.end, "--end") : today.toISOString().slice(0, 10);
|
|
2373
|
+
await mkdir(dir, { recursive: true });
|
|
2374
|
+
const userId = await resolveAthleteUserId(client);
|
|
2375
|
+
logErr(`exporting to ${dir} (user ${userId})`);
|
|
2376
|
+
const [summary, user, prefs, workouts, exercises, workingMaxes] = await Promise.all([
|
|
2377
|
+
fetchAthleteProfileSummary(client, userId),
|
|
2378
|
+
fetchAthleteUser(client, userId),
|
|
2379
|
+
fetchAthletePrefs(client),
|
|
2380
|
+
fetchAthleteWorkouts(client, start, end),
|
|
2381
|
+
fetchExerciseHistoryList(client),
|
|
2382
|
+
fetchWorkingMaxes(client)
|
|
2383
|
+
]);
|
|
2384
|
+
await writeFile(join(dir, "profile.json"), JSON.stringify({
|
|
2385
|
+
summary,
|
|
2386
|
+
user,
|
|
2387
|
+
prefs
|
|
2388
|
+
}, null, 2));
|
|
2389
|
+
await writeFile(join(dir, "workouts.json"), JSON.stringify(presentAthleteWorkouts(workouts), null, 2));
|
|
2390
|
+
await writeFile(join(dir, "exercises.json"), JSON.stringify(exercises, null, 2));
|
|
2391
|
+
await writeFile(join(dir, "working-maxes.json"), JSON.stringify(workingMaxes, null, 2));
|
|
2392
|
+
let histories = 0;
|
|
2393
|
+
if (values.full === true) {
|
|
2394
|
+
await mkdir(join(dir, "history"), { recursive: true });
|
|
2395
|
+
logErr(`fetching per-exercise history for ${exercises.length} exercises (--full)...`);
|
|
2396
|
+
await mapPool(exercises, 5, async (ex) => {
|
|
2397
|
+
const id = Number(ex.id);
|
|
2398
|
+
const detail = await fetchExerciseHistoryDetail(client, id, userId).catch(() => null);
|
|
2399
|
+
if (detail) {
|
|
2400
|
+
await writeFile(join(dir, "history", `${id}.json`), JSON.stringify(presentExerciseHistory(detail), null, 2));
|
|
2401
|
+
histories += 1;
|
|
2402
|
+
}
|
|
2403
|
+
});
|
|
2404
|
+
}
|
|
2405
|
+
out({
|
|
2406
|
+
exported: dir,
|
|
2407
|
+
range: {
|
|
2408
|
+
start,
|
|
2409
|
+
end
|
|
2410
|
+
},
|
|
2411
|
+
workouts: workouts.length,
|
|
2412
|
+
exercises: exercises.length,
|
|
2413
|
+
workingMaxes: workingMaxes.length,
|
|
2414
|
+
histories: values.full === true ? histories : "skipped (use --full)"
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
const LOG_SET_USAGE = "athlete log-set --date Y-M-D --set <id> <resultsJson> --yes";
|
|
2418
|
+
async function cmdAthleteLogSet(client, a) {
|
|
2419
|
+
const { values, positionals } = parse(a, {
|
|
2420
|
+
date: { type: "string" },
|
|
2421
|
+
set: { type: "string" },
|
|
2422
|
+
file: { type: "string" },
|
|
2423
|
+
yes: { type: "boolean" }
|
|
2424
|
+
});
|
|
2425
|
+
const date = isoDate(need(values.date, LOG_SET_USAGE), "--date");
|
|
2426
|
+
const savedWorkoutSetId = toInt(need(values.set, LOG_SET_USAGE), "--set");
|
|
2427
|
+
const args = validate(logSetArgsSchema, {
|
|
2428
|
+
date,
|
|
2429
|
+
savedWorkoutSetId,
|
|
2430
|
+
results: await jsonInput(positionals[0], values.file)
|
|
2431
|
+
}, "log-set args");
|
|
2432
|
+
if (values.yes !== true) fail(`logging to set ${savedWorkoutSetId} writes to your coach-visible log; add --yes.`);
|
|
2433
|
+
const mapped = args.results.map((r) => ({
|
|
2434
|
+
savedWorkoutSetExerciseId: toInt(String(r.savedWorkoutSetExerciseId), "savedWorkoutSetExerciseId"),
|
|
2435
|
+
sets: r.sets.map((s) => {
|
|
2436
|
+
const slot = {};
|
|
2437
|
+
if (s.param1 !== void 0) slot.param1 = s.param1;
|
|
2438
|
+
if (s.param2 !== void 0) slot.param2 = s.param2;
|
|
2439
|
+
return slot;
|
|
2440
|
+
})
|
|
2441
|
+
}));
|
|
2442
|
+
return out(await logAthleteSet(client, {
|
|
2443
|
+
date: args.date,
|
|
2444
|
+
savedWorkoutSetId,
|
|
2445
|
+
results: mapped
|
|
2446
|
+
}));
|
|
2447
|
+
}
|
|
2448
|
+
async function cmdAthlete(client, rest) {
|
|
2449
|
+
const [sub, ...a] = rest;
|
|
2450
|
+
switch (sub) {
|
|
1238
2451
|
case "whoami": return out(await get(client, "/user/simple"));
|
|
2452
|
+
case "profile": {
|
|
2453
|
+
const { values } = parse(a, { metric: { type: "boolean" } });
|
|
2454
|
+
const userId = await resolveAthleteUserId(client);
|
|
2455
|
+
const [summary, user] = await Promise.all([fetchAthleteProfileSummary(client, userId, values.metric === true), fetchAthleteUser(client, userId)]);
|
|
2456
|
+
return out({
|
|
2457
|
+
summary,
|
|
2458
|
+
user
|
|
2459
|
+
});
|
|
2460
|
+
}
|
|
2461
|
+
case "prefs": return out(await fetchAthletePrefs(client));
|
|
2462
|
+
case "workouts": {
|
|
2463
|
+
const { values } = parse(a, {
|
|
2464
|
+
start: { type: "string" },
|
|
2465
|
+
end: { type: "string" },
|
|
2466
|
+
raw: { type: "boolean" },
|
|
2467
|
+
"log-ids": { type: "boolean" },
|
|
2468
|
+
"logged-only": { type: "boolean" },
|
|
2469
|
+
limit: { type: "string" },
|
|
2470
|
+
summary: { type: "boolean" }
|
|
2471
|
+
});
|
|
2472
|
+
const workouts = await fetchAthleteWorkouts(client, isoDate(need(values.start, "athlete workouts --start Y-M-D --end Y-M-D"), "--start"), isoDate(need(values.end, "athlete workouts --start Y-M-D --end Y-M-D"), "--end"));
|
|
2473
|
+
if (values["log-ids"] === true) return out(presentLogTargets(workouts));
|
|
2474
|
+
if (values.raw === true) return out(workouts);
|
|
2475
|
+
const opts = {};
|
|
2476
|
+
if (values["logged-only"] === true) opts.loggedOnly = true;
|
|
2477
|
+
if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
|
|
2478
|
+
const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
|
|
2479
|
+
return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
|
|
2480
|
+
}
|
|
2481
|
+
case "exercises": {
|
|
2482
|
+
const { values } = parse(a, {
|
|
2483
|
+
q: { type: "string" },
|
|
2484
|
+
limit: { type: "string" }
|
|
2485
|
+
});
|
|
2486
|
+
const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
|
|
2487
|
+
const q = values.q;
|
|
2488
|
+
return out(q !== void 0 ? await searchExerciseHistory(client, q, limit) : await fetchExerciseHistoryList(client));
|
|
2489
|
+
}
|
|
2490
|
+
case "history": {
|
|
2491
|
+
const { values, positionals } = parse(a, { raw: { type: "boolean" } });
|
|
2492
|
+
const detail = await fetchExerciseHistoryDetail(client, toInt(need(positionals[0], "athlete history <exerciseId>"), "exerciseId"), await resolveAthleteUserId(client));
|
|
2493
|
+
return out(values.raw === true ? detail : presentExerciseHistory(detail));
|
|
2494
|
+
}
|
|
2495
|
+
case "prs": return out(await fetchPersonalRecords(client, toInt(need(a[0], "athlete prs <exerciseId>"), "exerciseId")));
|
|
2496
|
+
case "stats": {
|
|
2497
|
+
const { values, positionals } = parse(a, { date: { type: "string" } });
|
|
2498
|
+
const id = toInt(need(positionals[0], "athlete stats <exerciseId> --date Y-M-D"), "exerciseId");
|
|
2499
|
+
const date = isoDate(need(values.date, "athlete stats <exerciseId> --date Y-M-D"), "--date");
|
|
2500
|
+
return out(await fetchExerciseStats(client, id, await resolveAthleteUserId(client), date));
|
|
2501
|
+
}
|
|
2502
|
+
case "working-maxes": return out(await fetchWorkingMaxes(client));
|
|
2503
|
+
case "leaderboard": {
|
|
2504
|
+
const { values, positionals } = parse(a, {
|
|
2505
|
+
page: { type: "string" },
|
|
2506
|
+
"page-size": { type: "string" },
|
|
2507
|
+
gender: { type: "string" }
|
|
2508
|
+
});
|
|
2509
|
+
const workoutId = toInt(need(positionals[0], "athlete leaderboard <workoutId>"), "workoutId");
|
|
2510
|
+
const opts = {};
|
|
2511
|
+
if (values.page !== void 0) opts.page = toInt(values.page, "--page");
|
|
2512
|
+
if (values["page-size"] !== void 0) opts.pageSize = toInt(values["page-size"], "--page-size");
|
|
2513
|
+
if (values.gender !== void 0) opts.gender = toInt(values.gender, "--gender");
|
|
2514
|
+
return out(await fetchLeaderboard(client, workoutId, opts));
|
|
2515
|
+
}
|
|
2516
|
+
case "export": return cmdAthleteExport(client, a);
|
|
2517
|
+
case "log-set": return cmdAthleteLogSet(client, a);
|
|
2518
|
+
default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set>");
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
async function cmdSkill(rest) {
|
|
2522
|
+
const skillRoot = join(import.meta.dirname, "../skill");
|
|
2523
|
+
const positional = rest.find((r) => !r.startsWith("-"));
|
|
2524
|
+
if (positional === "list") return out((await readdir(skillRoot, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name));
|
|
2525
|
+
const name = positional ?? "trainheroic-unofficial";
|
|
2526
|
+
const dir = join(skillRoot, name);
|
|
2527
|
+
let text;
|
|
2528
|
+
try {
|
|
2529
|
+
text = await readFile(join(dir, "SKILL.md"), "utf8");
|
|
2530
|
+
} catch {
|
|
2531
|
+
return fail(`unknown skill "${name}". Run 'trainheroic skill list'.`);
|
|
2532
|
+
}
|
|
2533
|
+
process.stdout.write(text);
|
|
2534
|
+
if (rest.includes("--full")) try {
|
|
2535
|
+
const refDir = join(dir, "references");
|
|
2536
|
+
const refs = (await readdir(refDir)).filter((f) => f.endsWith(".md")).sort();
|
|
2537
|
+
for (const f of refs) {
|
|
2538
|
+
process.stdout.write(`\n\n===== references/${f} =====\n\n`);
|
|
2539
|
+
process.stdout.write(await readFile(join(refDir, f), "utf8"));
|
|
2540
|
+
}
|
|
2541
|
+
} catch {}
|
|
2542
|
+
}
|
|
2543
|
+
async function cmdInstallSkill() {
|
|
2544
|
+
const home = process.env.HOME ?? process.env.USERPROFILE;
|
|
2545
|
+
if (!home) fail("cannot determine home directory.");
|
|
2546
|
+
const skillRoot = join(import.meta.dirname, "../skill");
|
|
2547
|
+
const skillsDir = join(home, ".claude/skills");
|
|
2548
|
+
await mkdir(skillsDir, { recursive: true });
|
|
2549
|
+
const entries = await readdir(skillRoot, { withFileTypes: true });
|
|
2550
|
+
const installed = [];
|
|
2551
|
+
for (const entry of entries) {
|
|
2552
|
+
if (!entry.isDirectory()) continue;
|
|
2553
|
+
const dest = join(skillsDir, entry.name);
|
|
2554
|
+
await cp(join(skillRoot, entry.name), dest, {
|
|
2555
|
+
recursive: true,
|
|
2556
|
+
force: true
|
|
2557
|
+
});
|
|
2558
|
+
installed.push(dest);
|
|
2559
|
+
}
|
|
2560
|
+
out({ installed });
|
|
2561
|
+
}
|
|
2562
|
+
const COACH_USAGE = "usage: trainheroic coach <head-coach|athletes|programs|teams|notifications|analytics|program <id>|team <id>|team-codes <id>|roster-activity|athlete-training|athlete-lift-history|athlete-workouts|log-set|athlete-invite|athlete-archive|athlete-restore|team-create|team-update|team-delete|team-code-create|team-code-delete|session-copy|session-unpublish|session-save-template|analytics-query|exercise|workout|message>";
|
|
2563
|
+
const COACH_LOG_SET_USAGE = "coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson> --yes";
|
|
2564
|
+
async function cmdCoachLogSet(client, a) {
|
|
2565
|
+
const { values, positionals } = parse(a, {
|
|
2566
|
+
athlete: { type: "string" },
|
|
2567
|
+
date: { type: "string" },
|
|
2568
|
+
set: { type: "string" },
|
|
2569
|
+
file: { type: "string" },
|
|
2570
|
+
yes: { type: "boolean" }
|
|
2571
|
+
});
|
|
2572
|
+
const athleteId = toInt(need(values.athlete, COACH_LOG_SET_USAGE), "--athlete");
|
|
2573
|
+
const date = isoDate(need(values.date, COACH_LOG_SET_USAGE), "--date");
|
|
2574
|
+
const savedWorkoutSetId = toInt(need(values.set, COACH_LOG_SET_USAGE), "--set");
|
|
2575
|
+
const args = validate(coachLogSetArgsSchema, {
|
|
2576
|
+
athleteId,
|
|
2577
|
+
date,
|
|
2578
|
+
savedWorkoutSetId,
|
|
2579
|
+
results: await jsonInput(positionals[0], values.file)
|
|
2580
|
+
}, "coach log-set args");
|
|
2581
|
+
if (values.yes !== true) fail(`logging to athlete ${athleteId}'s set ${savedWorkoutSetId} writes to their training log; add --yes.`);
|
|
2582
|
+
const mapped = args.results.map((r) => ({
|
|
2583
|
+
savedWorkoutSetExerciseId: toInt(String(r.savedWorkoutSetExerciseId), "savedWorkoutSetExerciseId"),
|
|
2584
|
+
sets: r.sets.map((s) => {
|
|
2585
|
+
const slot = {};
|
|
2586
|
+
if (s.param1 !== void 0) slot.param1 = s.param1;
|
|
2587
|
+
if (s.param2 !== void 0) slot.param2 = s.param2;
|
|
2588
|
+
return slot;
|
|
2589
|
+
})
|
|
2590
|
+
}));
|
|
2591
|
+
return out(await logForAthlete(client, {
|
|
2592
|
+
athleteId,
|
|
2593
|
+
date: args.date,
|
|
2594
|
+
savedWorkoutSetId,
|
|
2595
|
+
results: mapped
|
|
2596
|
+
}));
|
|
2597
|
+
}
|
|
2598
|
+
async function cmdCoachAthleteWorkouts(client, a) {
|
|
2599
|
+
const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
|
|
2600
|
+
const { values } = parse(a, {
|
|
2601
|
+
athlete: { type: "string" },
|
|
2602
|
+
start: { type: "string" },
|
|
2603
|
+
end: { type: "string" },
|
|
2604
|
+
raw: { type: "boolean" },
|
|
2605
|
+
"log-ids": { type: "boolean" },
|
|
2606
|
+
"logged-only": { type: "boolean" },
|
|
2607
|
+
limit: { type: "string" },
|
|
2608
|
+
summary: { type: "boolean" }
|
|
2609
|
+
});
|
|
2610
|
+
const workouts = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
|
|
2611
|
+
if (values["log-ids"] === true) return out(presentLogTargets(workouts));
|
|
2612
|
+
if (values.raw === true) return out(workouts);
|
|
2613
|
+
const opts = {};
|
|
2614
|
+
if (values["logged-only"] === true) opts.loggedOnly = true;
|
|
2615
|
+
if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
|
|
2616
|
+
const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
|
|
2617
|
+
return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
|
|
2618
|
+
}
|
|
2619
|
+
async function cmdCoachRosterActivity(client, a) {
|
|
2620
|
+
const usage = "coach roster-activity --athletes <id,id,...> [--metric]";
|
|
2621
|
+
const { values } = parse(a, {
|
|
2622
|
+
athletes: { type: "string" },
|
|
2623
|
+
metric: { type: "boolean" }
|
|
2624
|
+
});
|
|
2625
|
+
return out(await fetchRosterActivity(client, idList(need(values.athletes, usage), "--athletes"), values.metric === true));
|
|
2626
|
+
}
|
|
2627
|
+
async function cmdCoachAthleteInvite(client, a) {
|
|
2628
|
+
const usage = "coach athlete-invite --team <id> --emails a@x,b@y [--message \"...\"] --yes";
|
|
2629
|
+
const { values } = parse(a, {
|
|
2630
|
+
team: { type: "string" },
|
|
2631
|
+
emails: { type: "string" },
|
|
2632
|
+
message: { type: "string" },
|
|
2633
|
+
yes: { type: "boolean" }
|
|
2634
|
+
});
|
|
2635
|
+
const teamId = toInt(need(values.team, usage), "--team");
|
|
2636
|
+
const emails = need(values.emails, usage).split(",").map((e) => e.trim()).filter((e) => e.length > 0);
|
|
2637
|
+
if (values.yes !== true) fail(`inviting ${emails.join(", ")} emails them a real invitation; add --yes.`);
|
|
2638
|
+
return out(await inviteAthletes(client, definedProps({
|
|
2639
|
+
teamId,
|
|
2640
|
+
emails,
|
|
2641
|
+
message: values.message
|
|
2642
|
+
})));
|
|
2643
|
+
}
|
|
2644
|
+
async function cmdCoachAthleteArchive(client, a) {
|
|
2645
|
+
const usage = "coach athlete-archive --athletes <id,id,...> --yes";
|
|
2646
|
+
const { values } = parse(a, {
|
|
2647
|
+
athletes: { type: "string" },
|
|
2648
|
+
yes: { type: "boolean" }
|
|
2649
|
+
});
|
|
2650
|
+
const athleteIds = idList(need(values.athletes, usage), "--athletes");
|
|
2651
|
+
if (values.yes !== true) fail(`archiving athlete(s) ${athleteIds.join(", ")} removes them from the active roster; add --yes.`);
|
|
2652
|
+
return out(await mutate(client, "PUT", "/v5/athletes/archive", { athleteIds }));
|
|
2653
|
+
}
|
|
2654
|
+
async function cmdCoachAthleteRestore(client, a) {
|
|
2655
|
+
const usage = "coach athlete-restore --athletes <id,id,...>";
|
|
2656
|
+
const { values } = parse(a, { athletes: { type: "string" } });
|
|
2657
|
+
return out(await mutate(client, "PUT", "/v5/athletes/restore", { athleteIds: idList(need(values.athletes, usage), "--athletes") }));
|
|
2658
|
+
}
|
|
2659
|
+
async function cmdCoachTeamCreate(client, a) {
|
|
2660
|
+
const { values } = parse(a, { title: { type: "string" } });
|
|
2661
|
+
return out(await mutate(client, "POST", "/1.0/coach/team/createWithTitleAndCode", { title: need(values.title, "coach team-create --title \"...\"") }));
|
|
2662
|
+
}
|
|
2663
|
+
async function cmdCoachTeamUpdate(client, a) {
|
|
2664
|
+
const usage = "coach team-update --team <id> --title \"...\"";
|
|
2665
|
+
const { values } = parse(a, {
|
|
2666
|
+
team: { type: "string" },
|
|
2667
|
+
title: { type: "string" }
|
|
2668
|
+
});
|
|
2669
|
+
const teamId = toInt(need(values.team, usage), "--team");
|
|
2670
|
+
const title = need(values.title, usage);
|
|
2671
|
+
return out(await mutate(client, "PUT", `/v5/teams/${teamId}`, { title }));
|
|
2672
|
+
}
|
|
2673
|
+
async function cmdCoachTeamDelete(client, a) {
|
|
2674
|
+
const usage = "coach team-delete --team <id> --yes";
|
|
2675
|
+
const { values } = parse(a, {
|
|
2676
|
+
team: { type: "string" },
|
|
2677
|
+
yes: { type: "boolean" }
|
|
2678
|
+
});
|
|
2679
|
+
const teamId = toInt(need(values.team, usage), "--team");
|
|
2680
|
+
if (values.yes !== true) fail(`deleting team ${teamId} removes it and its calendar; add --yes.`);
|
|
2681
|
+
return out(await mutate(client, "DELETE", `/v5/teams/${teamId}`));
|
|
2682
|
+
}
|
|
2683
|
+
async function cmdCoachTeamCodeCreate(client, a) {
|
|
2684
|
+
const usage = "coach team-code-create --team <id> [--type N]";
|
|
2685
|
+
const { values } = parse(a, {
|
|
2686
|
+
team: { type: "string" },
|
|
2687
|
+
type: { type: "string" }
|
|
2688
|
+
});
|
|
2689
|
+
const teamId = toInt(need(values.team, usage), "--team");
|
|
2690
|
+
const type = values.type !== void 0 ? toInt(values.type, "--type") : 2;
|
|
2691
|
+
return out(await mutate(client, "POST", `/v5/teams/${teamId}/teamCodes`, { type }));
|
|
2692
|
+
}
|
|
2693
|
+
async function cmdCoachTeamCodeDelete(client, a) {
|
|
2694
|
+
const usage = "coach team-code-delete --code <id> --yes";
|
|
2695
|
+
const { values } = parse(a, {
|
|
2696
|
+
code: { type: "string" },
|
|
2697
|
+
yes: { type: "boolean" }
|
|
2698
|
+
});
|
|
2699
|
+
const codeId = toInt(need(values.code, usage), "--code");
|
|
2700
|
+
if (values.yes !== true) fail(`deleting team code ${codeId} stops athletes joining with it; add --yes.`);
|
|
2701
|
+
return out(await mutate(client, "DELETE", `/v5/teamCodes/${codeId}`));
|
|
2702
|
+
}
|
|
2703
|
+
async function cmdCoachSessionCopy(client, a) {
|
|
2704
|
+
const usage = "coach session-copy --to-program <id> --pw <id> --to-date Y-M-D";
|
|
2705
|
+
const { values } = parse(a, {
|
|
2706
|
+
"to-program": { type: "string" },
|
|
2707
|
+
pw: { type: "string" },
|
|
2708
|
+
"to-date": { type: "string" }
|
|
2709
|
+
});
|
|
2710
|
+
return out(await copySession(client, {
|
|
2711
|
+
toProgramId: toInt(need(values["to-program"], usage), "--to-program"),
|
|
2712
|
+
pwId: toInt(need(values.pw, usage), "--pw"),
|
|
2713
|
+
toDate: need(values["to-date"], usage)
|
|
2714
|
+
}));
|
|
2715
|
+
}
|
|
2716
|
+
async function cmdCoachSessionUnpublish(client, a) {
|
|
2717
|
+
const usage = "coach session-unpublish --pw <id> --yes";
|
|
2718
|
+
const { values } = parse(a, {
|
|
2719
|
+
pw: { type: "string" },
|
|
2720
|
+
yes: { type: "boolean" }
|
|
2721
|
+
});
|
|
2722
|
+
const pwId = toInt(need(values.pw, usage), "--pw");
|
|
2723
|
+
if (values.yes !== true) fail(`unpublishing session ${pwId} hides it from the athlete; add --yes.`);
|
|
2724
|
+
return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`));
|
|
2725
|
+
}
|
|
2726
|
+
async function cmdCoachSessionSaveTemplate(client, a) {
|
|
2727
|
+
const usage = "coach session-save-template --workout <id>";
|
|
2728
|
+
const { values } = parse(a, { workout: { type: "string" } });
|
|
2729
|
+
return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${toInt(need(values.workout, usage), "--workout")}`));
|
|
2730
|
+
}
|
|
2731
|
+
async function cmdCoachAnalyticsQuery(client, a) {
|
|
2732
|
+
const { values } = parse(a, {
|
|
2733
|
+
metric: { type: "string" },
|
|
2734
|
+
team: { type: "string" },
|
|
2735
|
+
users: { type: "string" },
|
|
2736
|
+
exercise: { type: "string" },
|
|
2737
|
+
date: { type: "string" },
|
|
2738
|
+
start: { type: "string" },
|
|
2739
|
+
end: { type: "string" },
|
|
2740
|
+
"use-metric": { type: "boolean" }
|
|
2741
|
+
});
|
|
2742
|
+
if (values.metric === void 0) return out({
|
|
2743
|
+
note: "Pick a --metric from this catalog (these keys differ from the raw 'coach analytics' categories). 'requires'/'optional' are the flags each metric takes.",
|
|
2744
|
+
metrics: analyticsMetricCatalog()
|
|
2745
|
+
});
|
|
2746
|
+
const metric = values.metric;
|
|
2747
|
+
if (!ANALYTICS_METRIC_KEYS.includes(metric)) fail(`--metric "${metric}" is not valid. Choose one of: ${ANALYTICS_METRIC_KEYS.join(", ")}. Run 'coach analytics-query' with no --metric for each one's scope and required params.`);
|
|
2748
|
+
return out(await queryAnalytics(client, definedProps({
|
|
2749
|
+
metric,
|
|
2750
|
+
teamId: values.team !== void 0 ? toInt(values.team, "--team") : void 0,
|
|
2751
|
+
userIds: values.users !== void 0 ? idList(values.users, "--users") : void 0,
|
|
2752
|
+
exerciseId: values.exercise !== void 0 ? toInt(values.exercise, "--exercise") : void 0,
|
|
2753
|
+
date: values.date !== void 0 ? isoDate(values.date, "--date") : void 0,
|
|
2754
|
+
dateStart: values.start !== void 0 ? isoDate(values.start, "--start") : void 0,
|
|
2755
|
+
dateEnd: values.end !== void 0 ? isoDate(values.end, "--end") : void 0,
|
|
2756
|
+
useMetric: values["use-metric"] === true ? true : void 0
|
|
2757
|
+
})));
|
|
2758
|
+
}
|
|
2759
|
+
async function cmdCoachAthleteTraining(client, a) {
|
|
2760
|
+
const usage = "coach athlete-training --athlete <id> --year <YYYY> --month <1-12>";
|
|
2761
|
+
const { values } = parse(a, {
|
|
2762
|
+
athlete: { type: "string" },
|
|
2763
|
+
year: { type: "string" },
|
|
2764
|
+
month: { type: "string" }
|
|
2765
|
+
});
|
|
2766
|
+
const athleteId = toInt(need(values.athlete, usage), "--athlete");
|
|
2767
|
+
const year = toInt(need(values.year, usage), "--year");
|
|
2768
|
+
const month = toInt(need(values.month, usage), "--month");
|
|
2769
|
+
const view = presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(client, athleteId, year, month), athleteId, year, month);
|
|
2770
|
+
if (view.sessions.length === 0) return out({
|
|
2771
|
+
...view,
|
|
2772
|
+
note: `No logged sessions for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}. This is a per-month view of sessions the athlete actually logged (not prescribed work) — an empty list means nothing was logged that month, not an error. Try another month, or use 'coach athlete-workouts --athlete <id> --start <date> --end <date>' to see prescribed + logged work over a date range.`
|
|
2773
|
+
});
|
|
2774
|
+
return out(view);
|
|
2775
|
+
}
|
|
2776
|
+
async function cmdCoachAthleteLiftHistory(client, a) {
|
|
2777
|
+
const usage = "coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw]";
|
|
2778
|
+
const { values } = parse(a, {
|
|
2779
|
+
athlete: { type: "string" },
|
|
2780
|
+
exercise: { type: "string" },
|
|
2781
|
+
since: { type: "string" },
|
|
2782
|
+
until: { type: "string" },
|
|
2783
|
+
raw: { type: "boolean" }
|
|
2784
|
+
});
|
|
2785
|
+
const athleteId = toInt(need(values.athlete, usage), "--athlete");
|
|
2786
|
+
const exerciseId = toInt(need(values.exercise, usage), "--exercise");
|
|
2787
|
+
const detail = await fetchExerciseHistoryDetail(client, exerciseId, athleteId);
|
|
2788
|
+
if (values.raw === true) return out(detail);
|
|
2789
|
+
const presented = presentExerciseHistory(detail);
|
|
2790
|
+
const since = values.since !== void 0 ? isoDate(values.since, "--since") : void 0;
|
|
2791
|
+
const until = values.until !== void 0 ? isoDate(values.until, "--until") : void 0;
|
|
2792
|
+
const sessions = presented.sessions.filter((s) => (since === void 0 || s.date >= since) && (until === void 0 || s.date <= until));
|
|
2793
|
+
if (sessions.length === 0 && presented.liftPRs.length === 0) return out({
|
|
2794
|
+
...presented,
|
|
2795
|
+
sessions,
|
|
2796
|
+
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.`
|
|
2797
|
+
});
|
|
2798
|
+
return out({
|
|
2799
|
+
...presented,
|
|
2800
|
+
sessions
|
|
2801
|
+
});
|
|
2802
|
+
}
|
|
2803
|
+
async function cmdCoach(client, rest) {
|
|
2804
|
+
const [sub, ...a] = rest;
|
|
2805
|
+
switch (sub) {
|
|
1239
2806
|
case "head-coach": return out(await get(client, "/v5/headCoach"));
|
|
1240
2807
|
case "athletes": return out(await get(client, "/v5/athletes"));
|
|
1241
2808
|
case "programs": return out(await get(client, "/1.0/coach/programs"));
|
|
1242
2809
|
case "teams": return out(await get(client, "/1.0/coach/teams"));
|
|
1243
2810
|
case "notifications": return out(await get(client, "/v5/notifications/counts"));
|
|
1244
2811
|
case "analytics": return out(await get(client, "/v5/analytics"));
|
|
1245
|
-
case "program": return out(await get(client, `/3.0/coach/program/${encodeURIComponent(need(
|
|
1246
|
-
case "team": return out(await get(client, `/v5/teams/${encodeURIComponent(need(
|
|
1247
|
-
case "team-codes": return out(await get(client, `/v5/teams/${encodeURIComponent(need(
|
|
2812
|
+
case "program": return out(await get(client, `/3.0/coach/program/${encodeURIComponent(need(a[0], "coach program <id>"))}`));
|
|
2813
|
+
case "team": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team <id>"))}`));
|
|
2814
|
+
case "team-codes": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team-codes <id>"))}/teamCodes`));
|
|
2815
|
+
case "roster-activity": return cmdCoachRosterActivity(client, a);
|
|
2816
|
+
case "athlete-training": return cmdCoachAthleteTraining(client, a);
|
|
2817
|
+
case "athlete-lift-history": return cmdCoachAthleteLiftHistory(client, a);
|
|
2818
|
+
case "athlete-workouts": return cmdCoachAthleteWorkouts(client, a);
|
|
2819
|
+
case "log-set": return cmdCoachLogSet(client, a);
|
|
2820
|
+
case "athlete-invite": return cmdCoachAthleteInvite(client, a);
|
|
2821
|
+
case "athlete-archive": return cmdCoachAthleteArchive(client, a);
|
|
2822
|
+
case "athlete-restore": return cmdCoachAthleteRestore(client, a);
|
|
2823
|
+
case "team-create": return cmdCoachTeamCreate(client, a);
|
|
2824
|
+
case "team-update": return cmdCoachTeamUpdate(client, a);
|
|
2825
|
+
case "team-delete": return cmdCoachTeamDelete(client, a);
|
|
2826
|
+
case "team-code-create": return cmdCoachTeamCodeCreate(client, a);
|
|
2827
|
+
case "team-code-delete": return cmdCoachTeamCodeDelete(client, a);
|
|
2828
|
+
case "session-copy": return cmdCoachSessionCopy(client, a);
|
|
2829
|
+
case "session-unpublish": return cmdCoachSessionUnpublish(client, a);
|
|
2830
|
+
case "session-save-template": return cmdCoachSessionSaveTemplate(client, a);
|
|
2831
|
+
case "analytics-query": return cmdCoachAnalyticsQuery(client, a);
|
|
2832
|
+
case "exercise": return cmdExercise(client, a);
|
|
2833
|
+
case "workout": return cmdWorkout(client, a);
|
|
2834
|
+
case "message": return cmdMessage(client, a);
|
|
2835
|
+
default: return fail(COACH_USAGE);
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
async function dispatch(client, group, rest) {
|
|
2839
|
+
switch (group) {
|
|
2840
|
+
case "whoami": return out(await get(client, "/user/simple"));
|
|
1248
2841
|
case "request": return cmdRequest(client, rest);
|
|
1249
|
-
case "
|
|
1250
|
-
case "
|
|
1251
|
-
case "message": return cmdMessage(client, rest);
|
|
2842
|
+
case "coach": return cmdCoach(client, rest);
|
|
2843
|
+
case "athlete": return cmdAthlete(client, rest);
|
|
1252
2844
|
default: return fail(`unknown command "${group}". Run 'trainheroic help'.`);
|
|
1253
2845
|
}
|
|
1254
2846
|
}
|
|
@@ -1258,6 +2850,14 @@ async function main() {
|
|
|
1258
2850
|
process.stdout.write(HELP);
|
|
1259
2851
|
return;
|
|
1260
2852
|
}
|
|
2853
|
+
if (group === "install-skill") {
|
|
2854
|
+
await cmdInstallSkill();
|
|
2855
|
+
return;
|
|
2856
|
+
}
|
|
2857
|
+
if (group === "skill") {
|
|
2858
|
+
await cmdSkill(rest);
|
|
2859
|
+
return;
|
|
2860
|
+
}
|
|
1261
2861
|
const email = process.env.TRAINHEROIC_EMAIL;
|
|
1262
2862
|
const password = process.env.TRAINHEROIC_PASSWORD;
|
|
1263
2863
|
if (!email || !password) fail("set TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD in the environment.");
|