@trainheroic-unofficial/js 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -30
- package/dist/index.d.mts +64 -2
- package/dist/index.mjs +282 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# @trainheroic-unofficial/js
|
|
2
2
|
|
|
3
|
-
An unofficial TypeScript SDK for the TrainHeroic coaching API.
|
|
4
|
-
renewal
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
An unofficial TypeScript SDK for the TrainHeroic coaching API. The client covers auth and
|
|
4
|
+
session renewal across both TrainHeroic hosts, a searchable exercise library, workout
|
|
5
|
+
encoding, and messaging. It runs in any modern JavaScript runtime, including Cloudflare
|
|
6
|
+
workerd.
|
|
7
7
|
|
|
8
8
|
Part of the [trainheroic-unofficial](../../README.md) workspace.
|
|
9
9
|
|
|
@@ -73,7 +73,7 @@ const created = await client.request("POST", "/2.0/coach/exercise/create", {
|
|
|
73
73
|
});
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
The paths are the ones the TrainHeroic web app calls.
|
|
77
77
|
Most are reachable through the typed helpers below, so you rarely call `request` directly. The
|
|
78
78
|
request and response shapes those helpers use live in
|
|
79
79
|
[`@trainheroic-unofficial/dto`](../dto) as zod schemas and types.
|
|
@@ -86,7 +86,7 @@ life of the process, so a fresh process logs in again. To skip that login, read
|
|
|
86
86
|
one client and hand it to the next via the third constructor argument.
|
|
87
87
|
|
|
88
88
|
After a request has run, `client.sessionId` holds the active token, typed `string | null` (it
|
|
89
|
-
is `null` only before the first login). Persist it with your own storage
|
|
89
|
+
is `null` only before the first login). Persist it with your own storage; `saveToken` and
|
|
90
90
|
`loadToken` below stand in for whatever you use (a file, a KV store, an env var):
|
|
91
91
|
|
|
92
92
|
```ts
|
|
@@ -130,16 +130,17 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
|
|
|
130
130
|
client hit by concurrent requests performs a single shared login. `RequestOptions.base`
|
|
131
131
|
selects the host (`coach` for `api.trainheroic.com`, `apis` for `apis.trainheroic.com`).
|
|
132
132
|
- **Exercises.** `ExerciseIndex` is the interface the rest of the system codes against;
|
|
133
|
-
`ExerciseLibrary` is the in-memory implementation
|
|
134
|
-
fuzzy search, and
|
|
135
|
-
`./node`). The hosted server supplies a D1-backed implementation of the
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
133
|
+
`ExerciseLibrary` is the in-memory implementation, handling name-to-id resolution,
|
|
134
|
+
fuzzy search ranking, and persistence through a `LibraryCache` (in-memory by default,
|
|
135
|
+
JSON file via `./node`). The hosted server supplies a D1-backed implementation of the
|
|
136
|
+
same interface.
|
|
137
|
+
- **Workouts.** A session builder that creates a session, saves blocks and exercises,
|
|
138
|
+
and optionally publishes, along with read-back, instruction editing, and removal.
|
|
139
|
+
Includes the encoder that turns a `WorkoutSpec` into the API's payload.
|
|
140
|
+
- **Athlete training.** Functions for the logged-in account's own training, covering
|
|
141
|
+
scheduled and completed workouts, per-exercise history, personal records, and working maxes.
|
|
142
|
+
- **Messaging.** Tools for conversation streams: listing them, reading a stream, and
|
|
143
|
+
building or sending or deleting a comment.
|
|
143
144
|
|
|
144
145
|
## Working with exercises
|
|
145
146
|
|
|
@@ -171,8 +172,8 @@ if (!match) {
|
|
|
171
172
|
|
|
172
173
|
`buildSession` writes one session into a program on a given day: it creates the session, saves
|
|
173
174
|
the blocks and exercises, and optionally publishes. `programId` identifies one of your
|
|
174
|
-
TrainHeroic programs
|
|
175
|
-
|
|
175
|
+
TrainHeroic programs (find it in the program's URL in the web app, or from a programs read
|
|
176
|
+
via `client.request("GET", ...)`). Exercise ids come from the library.
|
|
176
177
|
|
|
177
178
|
```ts
|
|
178
179
|
import { buildSession, type BlockSpec } from "@trainheroic-unofficial/js";
|
|
@@ -203,13 +204,13 @@ Each exercise needs an `id`; `sets`, `reps`, `weight`, `rpe`, and a per-exercise
|
|
|
203
204
|
optional. `reps` and `weight` take a scalar (broadcast across every set) or a per-set array
|
|
204
205
|
like `reps: [5, 5, 3]`. The full field list is `ExerciseSpec` / `BlockSpec` in
|
|
205
206
|
[`@trainheroic-unofficial/dto`](../dto). Loads are in whatever unit the exercise is configured
|
|
206
|
-
for in TrainHeroic; a mismatch becomes an advisory
|
|
207
|
+
for in TrainHeroic; a mismatch becomes an advisory collected separately (see below).
|
|
207
208
|
|
|
208
|
-
`buildSession` returns `{ pwId, workoutId }`: `pwId` is the program-workout id (the
|
|
209
|
-
of the session in the program
|
|
210
|
-
the underlying workout id.
|
|
211
|
-
|
|
212
|
-
`removeSession(client, programId, pwId)
|
|
209
|
+
`buildSession` returns `{ pwId, workoutId }`: `pwId` is the program-workout id (the
|
|
210
|
+
placement of the session in the program, which is the handle subsequent calls take), and
|
|
211
|
+
`workoutId` is the underlying workout id. Use `pwId` with `readSession(client, programId, date, pwId)`
|
|
212
|
+
to read the session back. `publishSession(client, pwId)` publishes it later;
|
|
213
|
+
`removeSession(client, programId, pwId)` deletes it.
|
|
213
214
|
|
|
214
215
|
## Reading athlete training
|
|
215
216
|
|
|
@@ -228,13 +229,12 @@ scope.
|
|
|
228
229
|
`buildSession` calls the encoder for you; you only deal with it directly to preview warnings.
|
|
229
230
|
TrainHeroic's exercise payload expects every parameter slot present, so the encoder fills all
|
|
230
231
|
of them (empty slots included) to avoid an HTTP 500. A scalar prescription is broadcast across
|
|
231
|
-
the set count
|
|
232
|
-
|
|
233
|
-
|
|
232
|
+
the set count. RPE goes into the instruction text because the API coerces a numeric slot to
|
|
233
|
+
load. Unit mismatches between a spec and the exercise's fixed parameter types surface as
|
|
234
|
+
advisories preserved in the return value of `collectAdvisories`.
|
|
234
235
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
the unit notes and warnings for a set of blocks.
|
|
236
|
+
Call `collectAdvisories(blocks, index)` before building (the `index` is an `ExerciseLibrary`)
|
|
237
|
+
to get the unit notes and warnings for a set of blocks.
|
|
238
238
|
|
|
239
239
|
## Develop
|
|
240
240
|
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
|
|
2
|
-
import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, WorkoutDate } from "@trainheroic-unofficial/dto";
|
|
2
|
+
import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, TeamVolumeReport, WorkoutDate } from "@trainheroic-unofficial/dto";
|
|
3
3
|
import { ZodType } from "zod";
|
|
4
4
|
export * from "@trainheroic-unofficial/dto";
|
|
5
5
|
|
|
@@ -357,6 +357,48 @@ type AddedExercise = {
|
|
|
357
357
|
* logAthleteSet.
|
|
358
358
|
*/
|
|
359
359
|
declare function addExercisesToWorkout(client: TrainHeroicClient, workoutId: number, exercises: AddedExercise[]): Promise<unknown>;
|
|
360
|
+
/** One exercise's entered sets, keyed by the exercise id rather than a saved-set id. */
|
|
361
|
+
type SessionExercise = {
|
|
362
|
+
exerciseId: number;
|
|
363
|
+
order?: number;
|
|
364
|
+
sets: ReadonlyArray<{
|
|
365
|
+
param1?: number | string;
|
|
366
|
+
param2?: number | string;
|
|
367
|
+
}>;
|
|
368
|
+
};
|
|
369
|
+
/** Result of logging a session by exercise: which sets were written, and (athlete) whether a
|
|
370
|
+
* new personal session had to be created for the date. */
|
|
371
|
+
type LogSessionResult = {
|
|
372
|
+
date: string;
|
|
373
|
+
created: boolean;
|
|
374
|
+
sets: Array<{
|
|
375
|
+
savedWorkoutSetId: number;
|
|
376
|
+
exercisesLogged: number;
|
|
377
|
+
}>;
|
|
378
|
+
};
|
|
379
|
+
/**
|
|
380
|
+
* Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
|
|
381
|
+
* required. Reuses a personal session already on the date when one exists (the API marks these
|
|
382
|
+
* `personal_cal`), otherwise creates one; then adds the exercises and logs their entered sets.
|
|
383
|
+
* This is the "log whatever I just did" path — extra accessory work, a makeup lift, an off-plan
|
|
384
|
+
* gym session.
|
|
385
|
+
*/
|
|
386
|
+
declare function logAdHocSession(client: TrainHeroicClient, args: {
|
|
387
|
+
date: string;
|
|
388
|
+
exercises: readonly SessionExercise[];
|
|
389
|
+
}): Promise<LogSessionResult>;
|
|
390
|
+
/**
|
|
391
|
+
* Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
|
|
392
|
+
* off-plan session on another user's calendar (the personal-calendar endpoints are self-scoped),
|
|
393
|
+
* so this logs against the session the athlete already has on that date: each requested exercise
|
|
394
|
+
* is resolved to a prescribed saved set and its results are written via the coach "Log for
|
|
395
|
+
* Athlete" surface. Throws a readable error naming the prescribed exercises when one is missing.
|
|
396
|
+
*/
|
|
397
|
+
declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
398
|
+
athleteId: number;
|
|
399
|
+
date: string;
|
|
400
|
+
exercises: readonly SessionExercise[];
|
|
401
|
+
}): Promise<LogSessionResult>;
|
|
360
402
|
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
361
403
|
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
362
404
|
//#endregion
|
|
@@ -418,6 +460,26 @@ type AnalyticsQueryArgs = {
|
|
|
418
460
|
* athlete). Throws a readable Error when a required input is missing or the call fails.
|
|
419
461
|
*/
|
|
420
462
|
declare function queryAnalytics(client: TrainHeroicClient, args: AnalyticsQueryArgs): Promise<unknown>;
|
|
463
|
+
/**
|
|
464
|
+
* Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
|
|
465
|
+
* place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
|
|
466
|
+
* there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
|
|
467
|
+
* given id, matched as a string. Throws when the roster fetch fails.
|
|
468
|
+
*/
|
|
469
|
+
declare function fetchTeamAthleteIds(client: TrainHeroicClient, teamId: number): Promise<number[]>;
|
|
470
|
+
/**
|
|
471
|
+
* Team-wide training volume over an inclusive date window. The `training-summary-athlete`
|
|
472
|
+
* analytics report already returns the team in one call — one row per logged session across all
|
|
473
|
+
* `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
|
|
474
|
+
* volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
|
|
475
|
+
* logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
|
|
476
|
+
* all-time `fetchRosterActivity` snapshot, which has no date range.
|
|
477
|
+
*/
|
|
478
|
+
declare function teamVolume(client: TrainHeroicClient, args: {
|
|
479
|
+
athleteIds: readonly number[];
|
|
480
|
+
dateStart: string;
|
|
481
|
+
dateEnd: string;
|
|
482
|
+
}): Promise<TeamVolumeReport>;
|
|
421
483
|
//#endregion
|
|
422
484
|
//#region src/util.d.ts
|
|
423
485
|
/**
|
|
@@ -520,4 +582,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
520
582
|
stats(): Promise<Record<string, unknown>>;
|
|
521
583
|
}
|
|
522
584
|
//#endregion
|
|
523
|
-
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
585
|
+
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SessionExercise, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, teamVolume, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/dist/index.mjs
CHANGED
|
@@ -950,6 +950,199 @@ async function addExercisesToWorkout(client, workoutId, exercises) {
|
|
|
950
950
|
if (!res.ok) throw new Error(`Add exercises to workout failed (HTTP ${res.status}).`);
|
|
951
951
|
return res.data;
|
|
952
952
|
}
|
|
953
|
+
/**
|
|
954
|
+
* Find a personal-calendar session already on the given day. The range marks these with
|
|
955
|
+
* `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
|
|
956
|
+
* first one's workoutId, or null when the day has no personal session.
|
|
957
|
+
*/
|
|
958
|
+
function findPersonalSessionWorkoutId(workouts) {
|
|
959
|
+
for (const pw of workouts) {
|
|
960
|
+
const rec = pw;
|
|
961
|
+
if (rec.personal_cal === true) {
|
|
962
|
+
const workoutId = coerceInt(rec.workout_id);
|
|
963
|
+
if (workoutId !== null) return workoutId;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return null;
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* Map the `addExercisesToWorkout` response (an array of saved sets) to per-exercise saved ids.
|
|
970
|
+
* Each set's `id` is a savedWorkoutSetId; each `savedWorkoutSetExercises[].id` is a
|
|
971
|
+
* savedWorkoutSetExerciseId and `.exerciseId` is the catalog exercise id that was added.
|
|
972
|
+
*/
|
|
973
|
+
function indexAddedExercises(added) {
|
|
974
|
+
const out = [];
|
|
975
|
+
const sets = Array.isArray(added) ? added : [];
|
|
976
|
+
for (const s of sets) {
|
|
977
|
+
if (!isRecord(s)) continue;
|
|
978
|
+
const savedWorkoutSetId = coerceInt(s.id);
|
|
979
|
+
if (savedWorkoutSetId === null) continue;
|
|
980
|
+
const exercises = Array.isArray(s.savedWorkoutSetExercises) ? s.savedWorkoutSetExercises : [];
|
|
981
|
+
for (const ex of exercises) {
|
|
982
|
+
if (!isRecord(ex)) continue;
|
|
983
|
+
const savedWorkoutSetExerciseId = coerceInt(ex.id);
|
|
984
|
+
const exerciseId = coerceInt(ex.exerciseId ?? ex.exercise_id);
|
|
985
|
+
if (savedWorkoutSetExerciseId === null || exerciseId === null) continue;
|
|
986
|
+
out.push({
|
|
987
|
+
exerciseId,
|
|
988
|
+
savedWorkoutSetId,
|
|
989
|
+
savedWorkoutSetExerciseId
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
return out;
|
|
994
|
+
}
|
|
995
|
+
/** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
|
|
996
|
+
function eachPrescribedExercise(workouts) {
|
|
997
|
+
const rows = [];
|
|
998
|
+
for (const pw of workouts) {
|
|
999
|
+
const rec = pw;
|
|
1000
|
+
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
1001
|
+
const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
1002
|
+
if (!sw) continue;
|
|
1003
|
+
const sets = [...Array.isArray(sw.workoutSets) ? sw.workoutSets : [], ...Array.isArray(sw.addedWorkoutSets) ? sw.addedWorkoutSets : []];
|
|
1004
|
+
for (const s of sets) {
|
|
1005
|
+
if (!isRecord(s)) continue;
|
|
1006
|
+
const savedWorkoutSetId = coerceInt(s.id);
|
|
1007
|
+
if (savedWorkoutSetId === null) continue;
|
|
1008
|
+
const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
1009
|
+
for (const ex of exercises) if (isRecord(ex)) rows.push({
|
|
1010
|
+
savedWorkoutSetId,
|
|
1011
|
+
ex
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return rows;
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* Locate a single prescribed exercise on the given day's workouts, returning the saved set it
|
|
1019
|
+
* belongs to and its saved-set-exercise id. Used by the coach path, which can only log against
|
|
1020
|
+
* what is already on the athlete's calendar. Returns null when the exercise is not prescribed
|
|
1021
|
+
* that day.
|
|
1022
|
+
*/
|
|
1023
|
+
function findPrescribedExercise(workouts, exerciseId, used) {
|
|
1024
|
+
for (const { savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
|
|
1025
|
+
const sweId = coerceInt(ex.id);
|
|
1026
|
+
if (sweId === null || used.has(sweId)) continue;
|
|
1027
|
+
if (coerceInt(ex.exercise_id) === exerciseId) return {
|
|
1028
|
+
savedWorkoutSetId,
|
|
1029
|
+
savedWorkoutSetExerciseId: sweId
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
return null;
|
|
1033
|
+
}
|
|
1034
|
+
/** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
|
|
1035
|
+
function prescribedExerciseLabels(workouts) {
|
|
1036
|
+
const labels = [];
|
|
1037
|
+
for (const { ex } of eachPrescribedExercise(workouts)) {
|
|
1038
|
+
const id = coerceInt(ex.exercise_id);
|
|
1039
|
+
if (id === null) continue;
|
|
1040
|
+
const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
|
|
1041
|
+
labels.push(`${id} (${title})`);
|
|
1042
|
+
}
|
|
1043
|
+
return labels;
|
|
1044
|
+
}
|
|
1045
|
+
/** Group resolved exercises by saved set and write each set via the given log target. */
|
|
1046
|
+
async function logResolvedExercises(client, target, date, resolved) {
|
|
1047
|
+
const bySet = /* @__PURE__ */ new Map();
|
|
1048
|
+
for (const r of resolved) {
|
|
1049
|
+
const list = bySet.get(r.savedWorkoutSetId) ?? [];
|
|
1050
|
+
list.push({
|
|
1051
|
+
savedWorkoutSetExerciseId: r.savedWorkoutSetExerciseId,
|
|
1052
|
+
sets: [...r.sets]
|
|
1053
|
+
});
|
|
1054
|
+
bySet.set(r.savedWorkoutSetId, list);
|
|
1055
|
+
}
|
|
1056
|
+
const out = [];
|
|
1057
|
+
for (const [savedWorkoutSetId, results] of bySet) {
|
|
1058
|
+
const written = target.role === "coach" ? await logForAthlete(client, {
|
|
1059
|
+
athleteId: target.athleteId,
|
|
1060
|
+
date,
|
|
1061
|
+
savedWorkoutSetId,
|
|
1062
|
+
results
|
|
1063
|
+
}) : await logAthleteSet(client, {
|
|
1064
|
+
date,
|
|
1065
|
+
savedWorkoutSetId,
|
|
1066
|
+
results
|
|
1067
|
+
});
|
|
1068
|
+
out.push(written);
|
|
1069
|
+
}
|
|
1070
|
+
return out;
|
|
1071
|
+
}
|
|
1072
|
+
/**
|
|
1073
|
+
* Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
|
|
1074
|
+
* required. Reuses a personal session already on the date when one exists (the API marks these
|
|
1075
|
+
* `personal_cal`), otherwise creates one; then adds the exercises and logs their entered sets.
|
|
1076
|
+
* This is the "log whatever I just did" path — extra accessory work, a makeup lift, an off-plan
|
|
1077
|
+
* gym session.
|
|
1078
|
+
*/
|
|
1079
|
+
async function logAdHocSession(client, args) {
|
|
1080
|
+
if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
|
|
1081
|
+
const existing = findPersonalSessionWorkoutId(await fetchAthleteWorkouts(client, args.date, args.date));
|
|
1082
|
+
const created = existing === null;
|
|
1083
|
+
const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
|
|
1084
|
+
const withOrder = args.exercises.map((e, i) => ({
|
|
1085
|
+
...e,
|
|
1086
|
+
order: e.order ?? i + 1
|
|
1087
|
+
}));
|
|
1088
|
+
const index = indexAddedExercises(await addExercisesToWorkout(client, workoutId, withOrder.map((e) => ({
|
|
1089
|
+
exerciseId: e.exerciseId,
|
|
1090
|
+
order: e.order
|
|
1091
|
+
}))));
|
|
1092
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
1093
|
+
const resolved = withOrder.map((e) => {
|
|
1094
|
+
const hit = index.find((m) => m.exerciseId === e.exerciseId && !consumed.has(m.savedWorkoutSetExerciseId));
|
|
1095
|
+
if (!hit) throw new Error(`Could not place exercise ${e.exerciseId} into the session after adding it. The add-exercises response did not return a saved set for it.`);
|
|
1096
|
+
consumed.add(hit.savedWorkoutSetExerciseId);
|
|
1097
|
+
return {
|
|
1098
|
+
exerciseId: e.exerciseId,
|
|
1099
|
+
savedWorkoutSetId: hit.savedWorkoutSetId,
|
|
1100
|
+
savedWorkoutSetExerciseId: hit.savedWorkoutSetExerciseId,
|
|
1101
|
+
sets: e.sets
|
|
1102
|
+
};
|
|
1103
|
+
});
|
|
1104
|
+
const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
|
|
1105
|
+
return {
|
|
1106
|
+
date: args.date,
|
|
1107
|
+
created,
|
|
1108
|
+
sets
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
|
|
1113
|
+
* off-plan session on another user's calendar (the personal-calendar endpoints are self-scoped),
|
|
1114
|
+
* so this logs against the session the athlete already has on that date: each requested exercise
|
|
1115
|
+
* is resolved to a prescribed saved set and its results are written via the coach "Log for
|
|
1116
|
+
* Athlete" surface. Throws a readable error naming the prescribed exercises when one is missing.
|
|
1117
|
+
*/
|
|
1118
|
+
async function logSessionForAthlete(client, args) {
|
|
1119
|
+
if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
|
|
1120
|
+
const day = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
|
|
1121
|
+
const used = /* @__PURE__ */ new Set();
|
|
1122
|
+
const resolved = args.exercises.map((e) => {
|
|
1123
|
+
const hit = findPrescribedExercise(day, e.exerciseId, used);
|
|
1124
|
+
if (!hit) {
|
|
1125
|
+
const labels = prescribedExerciseLabels(day);
|
|
1126
|
+
const present = labels.length > 0 ? `Prescribed on ${args.date}: ${labels.join(", ")}.` : `Nothing is prescribed for athlete ${args.athleteId} on ${args.date}.`;
|
|
1127
|
+
throw new Error(`Exercise ${e.exerciseId} is not on athlete ${args.athleteId}'s calendar for ${args.date}, so there is no set to log it against. ${present} A coach can only log against an existing session; build/publish a session for the athlete first if it is missing.`);
|
|
1128
|
+
}
|
|
1129
|
+
used.add(hit.savedWorkoutSetExerciseId);
|
|
1130
|
+
return {
|
|
1131
|
+
exerciseId: e.exerciseId,
|
|
1132
|
+
...hit,
|
|
1133
|
+
sets: e.sets
|
|
1134
|
+
};
|
|
1135
|
+
});
|
|
1136
|
+
const sets = await logResolvedExercises(client, {
|
|
1137
|
+
role: "coach",
|
|
1138
|
+
athleteId: args.athleteId
|
|
1139
|
+
}, args.date, resolved);
|
|
1140
|
+
return {
|
|
1141
|
+
date: args.date,
|
|
1142
|
+
created: false,
|
|
1143
|
+
sets
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
953
1146
|
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
954
1147
|
function presentExerciseHistory(detail) {
|
|
955
1148
|
return {
|
|
@@ -1167,6 +1360,94 @@ async function queryAnalytics(client, args) {
|
|
|
1167
1360
|
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
1168
1361
|
return res.data;
|
|
1169
1362
|
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
|
|
1365
|
+
* place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
|
|
1366
|
+
* there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
|
|
1367
|
+
* given id, matched as a string. Throws when the roster fetch fails.
|
|
1368
|
+
*/
|
|
1369
|
+
async function fetchTeamAthleteIds(client, teamId) {
|
|
1370
|
+
const res = await client.request("GET", "/v5/athletes");
|
|
1371
|
+
if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
|
|
1372
|
+
const rows = Array.isArray(res.data) ? res.data : [];
|
|
1373
|
+
const want = String(teamId);
|
|
1374
|
+
const ids = [];
|
|
1375
|
+
for (const row of rows) {
|
|
1376
|
+
if (row === null || typeof row !== "object") continue;
|
|
1377
|
+
const rec = row;
|
|
1378
|
+
if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
|
|
1379
|
+
const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
|
|
1380
|
+
if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
|
|
1381
|
+
}
|
|
1382
|
+
return ids;
|
|
1383
|
+
}
|
|
1384
|
+
function toNum(v) {
|
|
1385
|
+
const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
|
|
1386
|
+
return Number.isFinite(n) ? n : 0;
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* Team-wide training volume over an inclusive date window. The `training-summary-athlete`
|
|
1390
|
+
* analytics report already returns the team in one call — one row per logged session across all
|
|
1391
|
+
* `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
|
|
1392
|
+
* volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
|
|
1393
|
+
* logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
|
|
1394
|
+
* all-time `fetchRosterActivity` snapshot, which has no date range.
|
|
1395
|
+
*/
|
|
1396
|
+
async function teamVolume(client, args) {
|
|
1397
|
+
if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
|
|
1398
|
+
const report = await queryAnalytics(client, {
|
|
1399
|
+
metric: "training-summary-athlete",
|
|
1400
|
+
userIds: args.athleteIds,
|
|
1401
|
+
dateStart: args.dateStart,
|
|
1402
|
+
dateEnd: args.dateEnd
|
|
1403
|
+
});
|
|
1404
|
+
const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
|
|
1405
|
+
const byAthlete = /* @__PURE__ */ new Map();
|
|
1406
|
+
for (const row of rows) {
|
|
1407
|
+
const athleteId = toNum(row.user_id);
|
|
1408
|
+
if (athleteId === 0) continue;
|
|
1409
|
+
const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
|
|
1410
|
+
const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
|
|
1411
|
+
const existing = byAthlete.get(athleteId);
|
|
1412
|
+
if (existing) {
|
|
1413
|
+
existing.sessions += 1;
|
|
1414
|
+
existing.reps += toNum(row.reps);
|
|
1415
|
+
existing.volume += toNum(row.volume);
|
|
1416
|
+
if (date !== null) {
|
|
1417
|
+
if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
|
|
1418
|
+
if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
|
|
1419
|
+
}
|
|
1420
|
+
} else byAthlete.set(athleteId, {
|
|
1421
|
+
athleteId,
|
|
1422
|
+
name,
|
|
1423
|
+
sessions: 1,
|
|
1424
|
+
reps: toNum(row.reps),
|
|
1425
|
+
volume: toNum(row.volume),
|
|
1426
|
+
firstLoggedDate: date,
|
|
1427
|
+
lastLoggedDate: date
|
|
1428
|
+
});
|
|
1429
|
+
}
|
|
1430
|
+
const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
|
|
1431
|
+
const totals = athletes.reduce((acc, a) => ({
|
|
1432
|
+
athletes: acc.athletes + 1,
|
|
1433
|
+
sessions: acc.sessions + a.sessions,
|
|
1434
|
+
reps: acc.reps + a.reps,
|
|
1435
|
+
volume: acc.volume + a.volume
|
|
1436
|
+
}), {
|
|
1437
|
+
athletes: 0,
|
|
1438
|
+
sessions: 0,
|
|
1439
|
+
reps: 0,
|
|
1440
|
+
volume: 0
|
|
1441
|
+
});
|
|
1442
|
+
return {
|
|
1443
|
+
window: {
|
|
1444
|
+
start: args.dateStart,
|
|
1445
|
+
end: args.dateEnd
|
|
1446
|
+
},
|
|
1447
|
+
athletes,
|
|
1448
|
+
totals
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1170
1451
|
//#endregion
|
|
1171
1452
|
//#region src/util.ts
|
|
1172
1453
|
/**
|
|
@@ -1750,4 +2031,4 @@ var ExerciseLibrary = class {
|
|
|
1750
2031
|
}
|
|
1751
2032
|
};
|
|
1752
2033
|
//#endregion
|
|
1753
|
-
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
2034
|
+
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, teamVolume, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"zod": "^4.4.3",
|
|
30
|
-
"@trainheroic-unofficial/dto": "1.
|
|
30
|
+
"@trainheroic-unofficial/dto": "1.1.1"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.0.0",
|