@trainheroic-unofficial/js 1.6.1 → 1.7.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 +35 -0
- package/dist/index.d.mts +66 -13
- package/dist/index.mjs +386 -85
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ Part of the [trainheroic-unofficial](../../README.md) workspace.
|
|
|
19
19
|
- [Working with exercises](#working-with-exercises)
|
|
20
20
|
- [Building a workout](#building-a-workout)
|
|
21
21
|
- [Reading athlete training](#reading-athlete-training)
|
|
22
|
+
- [Analytics](#analytics)
|
|
22
23
|
- [The workout encoder](#the-workout-encoder)
|
|
23
24
|
- [Develop](#develop)
|
|
24
25
|
|
|
@@ -139,6 +140,9 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
|
|
|
139
140
|
Includes the encoder that turns a `WorkoutSpec` into the API's payload.
|
|
140
141
|
- **Athlete training.** Functions for the logged-in account's own training, covering
|
|
141
142
|
scheduled and completed workouts, per-exercise history, personal records, and working maxes.
|
|
143
|
+
- **Analytics.** Coach analytics reports via `queryAnalytics`, with `analyticsMetricCatalog`
|
|
144
|
+
and `ANALYTICS_METRIC_KEYS` for discovery. `teamVolume` rolls up per-athlete training
|
|
145
|
+
summary rows into a team total.
|
|
142
146
|
- **Messaging.** Tools for conversation streams: listing them, reading a stream, and
|
|
143
147
|
building or sending or deleting a comment.
|
|
144
148
|
|
|
@@ -224,6 +228,37 @@ const summary = await fetchAthleteProfileSummary(client, userId);
|
|
|
224
228
|
These work from any session, coach or athlete, since a coach account also carries athlete
|
|
225
229
|
scope.
|
|
226
230
|
|
|
231
|
+
## Analytics
|
|
232
|
+
|
|
233
|
+
Coach analytics reports are read-only data pulls. TrainHeroic uses POST for these queries, but
|
|
234
|
+
they do not mutate anything. The `metric` keys in `ANALYTICS_METRIC_KEYS` are the SDK catalog
|
|
235
|
+
— they are not the raw category names from `GET /v5/analytics`. Use `analyticsMetricCatalog()`
|
|
236
|
+
to see each metric's scope and required inputs.
|
|
237
|
+
|
|
238
|
+
Team metrics (`readiness-team`, `compliance-team`, `lift-progress-team`) need `teamId`.
|
|
239
|
+
Athlete metrics (`readiness-athlete`, `training-summary-athlete`, `lift-1rm-history`,
|
|
240
|
+
`working-max-history`) need one or more `userIds` in a single call (the report returns a row
|
|
241
|
+
per athlete). `readiness-team` takes a single `date`; every other metric takes `dateStart` and
|
|
242
|
+
`dateEnd`. Lift metrics also need `exerciseId`. All dates are `YYYY-MM-DD`.
|
|
243
|
+
|
|
244
|
+
There is no team-wide training volume metric. Pass every athlete's id to
|
|
245
|
+
`training-summary-athlete`, or call `teamVolume()` to group those rows into a team rollup.
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
import { analyticsMetricCatalog, queryAnalytics } from "@trainheroic-unofficial/js";
|
|
249
|
+
|
|
250
|
+
// Read-only report (TrainHeroic uses POST for these queries).
|
|
251
|
+
const readiness = await queryAnalytics(client, {
|
|
252
|
+
metric: "readiness-team",
|
|
253
|
+
teamId: 42,
|
|
254
|
+
date: "2026-06-22",
|
|
255
|
+
});
|
|
256
|
+
console.log(readiness);
|
|
257
|
+
|
|
258
|
+
// Scope + required params for every metric key:
|
|
259
|
+
console.log(analyticsMetricCatalog());
|
|
260
|
+
```
|
|
261
|
+
|
|
227
262
|
## The workout encoder
|
|
228
263
|
|
|
229
264
|
`buildSession` calls the encoder for you; you only deal with it directly to preview warnings.
|
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, TeamVolumeReport, 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, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
|
|
3
3
|
import { ZodType } from "zod";
|
|
4
4
|
export * from "@trainheroic-unofficial/dto";
|
|
5
5
|
|
|
@@ -175,6 +175,29 @@ declare function fetchPersonalRecords(client: TrainHeroicClient, exerciseId: num
|
|
|
175
175
|
declare function fetchExerciseStats(client: TrainHeroicClient, exerciseId: number, userId: number, date: string): Promise<ExerciseStats>;
|
|
176
176
|
/** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
|
|
177
177
|
declare function fetchAthleteWorkouts(client: TrainHeroicClient, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
|
|
178
|
+
/** Split an inclusive `[start, end]` range into consecutive non-overlapping windows of `windowDays`. */
|
|
179
|
+
declare function dateWindows(startDate: string, endDate: string, windowDays: number): Array<{
|
|
180
|
+
start: string;
|
|
181
|
+
end: string;
|
|
182
|
+
}>;
|
|
183
|
+
/**
|
|
184
|
+
* Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
|
|
185
|
+
* window boundary must not double up, first occurrence wins), then sorted oldest-first by date so
|
|
186
|
+
* the order is stable regardless of window seams. Id-less rows are kept and appended.
|
|
187
|
+
*/
|
|
188
|
+
declare function mergeWorkoutsById(pages: readonly ProgramWorkout[][]): ProgramWorkout[];
|
|
189
|
+
/**
|
|
190
|
+
* Fetch an athlete's workouts across a long range by splitting it into windows and fetching them
|
|
191
|
+
* with bounded concurrency, then merging (deduped by workout id, sorted oldest-first). The
|
|
192
|
+
* `programworkout/range` endpoint 504s on a multi-year span, so a full-history export must chunk.
|
|
193
|
+
* `windowDays` defaults to 180; `onProgress(done, total)` reports completed windows for a progress
|
|
194
|
+
* indicator. A range that fits one window delegates to the plain fetch (API order preserved).
|
|
195
|
+
*/
|
|
196
|
+
declare function fetchAthleteWorkoutsChunked(client: TrainHeroicClient, startDate: string, endDate: string, opts?: {
|
|
197
|
+
windowDays?: number;
|
|
198
|
+
concurrency?: number;
|
|
199
|
+
onProgress?: (done: number, total: number) => void;
|
|
200
|
+
}): Promise<ProgramWorkout[]>;
|
|
178
201
|
/**
|
|
179
202
|
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
180
203
|
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
@@ -195,14 +218,16 @@ declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number,
|
|
|
195
218
|
gender?: number;
|
|
196
219
|
}): Promise<unknown>;
|
|
197
220
|
/**
|
|
198
|
-
* Flatten one
|
|
199
|
-
*
|
|
200
|
-
*
|
|
201
|
-
* `performed` sets; athlete-added/personal work that has no prescription is appended as its
|
|
202
|
-
* own blocks. No `raw` is needed to see logged results.
|
|
221
|
+
* Flatten one range item into a readable workout: each exercise carries its `prescribed` and
|
|
222
|
+
* `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
|
|
223
|
+
* prescription is appended as its own blocks. No `raw` is needed to see logged results.
|
|
203
224
|
*/
|
|
204
225
|
declare function presentAthleteWorkout(raw: ProgramWorkout): AthleteWorkoutView;
|
|
205
226
|
declare function presentAthleteWorkouts(list: readonly ProgramWorkout[]): AthleteWorkoutView[];
|
|
227
|
+
/** Flatten one workout into the structured export shape (numeric sets), from the same merge as
|
|
228
|
+
* {@link presentAthleteWorkout}. */
|
|
229
|
+
declare function presentAthleteWorkoutExport(raw: ProgramWorkout): WorkoutHistoryExport;
|
|
230
|
+
declare function presentAthleteWorkoutsExport(list: readonly ProgramWorkout[]): WorkoutHistoryExport[];
|
|
206
231
|
/** The minimal id scaffold `log-set` / `logForAthlete` needs for one saved workout set. */
|
|
207
232
|
type LogSetTarget = {
|
|
208
233
|
date: string;
|
|
@@ -245,15 +270,19 @@ declare function selectWorkoutsByProgram(list: readonly ProgramWorkout[], filter
|
|
|
245
270
|
*/
|
|
246
271
|
declare function presentLogTargets(list: readonly ProgramWorkout[]): LogSetTarget[];
|
|
247
272
|
/**
|
|
248
|
-
* Narrow a
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
273
|
+
* Narrow a workout list for the common "what did I actually do" reads. `loggedOnly` keeps only
|
|
274
|
+
* workouts the athlete logged a set on (the reliable signal, not the API's completion flag).
|
|
275
|
+
* `limit` keeps the most recent N by date (newest first). Both are pure post-filters; the raw API
|
|
276
|
+
* path is left untouched. Generic over the presented (`AthleteWorkoutView`) and exported
|
|
277
|
+
* (`WorkoutHistoryExport`) shapes, which both carry `date` and `logged`, so one rule serves both.
|
|
252
278
|
*/
|
|
253
|
-
declare function selectWorkouts
|
|
279
|
+
declare function selectWorkouts<T extends {
|
|
280
|
+
date: string;
|
|
281
|
+
logged: boolean;
|
|
282
|
+
}>(list: readonly T[], opts?: {
|
|
254
283
|
loggedOnly?: boolean;
|
|
255
284
|
limit?: number;
|
|
256
|
-
}):
|
|
285
|
+
}): T[];
|
|
257
286
|
/**
|
|
258
287
|
* Project presented workouts to compact headers (date/title/program + logged flag + exercise
|
|
259
288
|
* counts), dropping the per-set block detail. A dense multi-program week of full views can be
|
|
@@ -565,6 +594,30 @@ declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
|
565
594
|
exercises: readonly SessionExercise[];
|
|
566
595
|
}): Promise<LogSessionResult>;
|
|
567
596
|
//#endregion
|
|
597
|
+
//#region src/workout-export.d.ts
|
|
598
|
+
type WorkoutExportFormat = "json" | "csv" | "text";
|
|
599
|
+
/** A serialized export ready to write to a file or hand to a browser download. */
|
|
600
|
+
type SerializedExport = {
|
|
601
|
+
content: string;
|
|
602
|
+
contentType: string;
|
|
603
|
+
extension: string;
|
|
604
|
+
filename: string;
|
|
605
|
+
};
|
|
606
|
+
/** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
|
|
607
|
+
declare function workoutsToJson(workouts: readonly WorkoutHistoryExport[]): string;
|
|
608
|
+
/**
|
|
609
|
+
* One row per set. `reps`/`weight` columns hold the broken-out numeric values for the common
|
|
610
|
+
* lifting case; the trailing `prescribed`/`performed` columns hold the raw `"p1 @ p2"` display so a
|
|
611
|
+
* time, distance, or percentage exercise (where the reps/weight columns are blank) loses nothing.
|
|
612
|
+
*/
|
|
613
|
+
declare function workoutsToCsv(workouts: readonly WorkoutHistoryExport[]): string;
|
|
614
|
+
/** A readable, indented rendering — one athlete-friendly block of text per session. */
|
|
615
|
+
declare function workoutsToText(workouts: readonly WorkoutHistoryExport[]): string;
|
|
616
|
+
/** Serialize the workout history to the chosen format, with content-type and a suggested filename. */
|
|
617
|
+
declare function serializeWorkoutHistory(workouts: readonly WorkoutHistoryExport[], format: WorkoutExportFormat, opts?: {
|
|
618
|
+
filenameBase?: string;
|
|
619
|
+
}): SerializedExport;
|
|
620
|
+
//#endregion
|
|
568
621
|
//#region src/main-lifts.d.ts
|
|
569
622
|
type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
|
|
570
623
|
type MainLiftFamily = {
|
|
@@ -839,4 +892,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
839
892
|
stats(): Promise<Record<string, unknown>>;
|
|
840
893
|
}
|
|
841
894
|
//#endregion
|
|
842
|
-
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
895
|
+
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
package/dist/index.mjs
CHANGED
|
@@ -451,6 +451,66 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
|
|
|
451
451
|
function fetchAthleteWorkouts(client, startDate, endDate) {
|
|
452
452
|
return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
|
|
453
453
|
}
|
|
454
|
+
/** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
|
|
455
|
+
function shiftDate(iso, days) {
|
|
456
|
+
const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
|
|
457
|
+
d.setUTCDate(d.getUTCDate() + days);
|
|
458
|
+
return d.toISOString().slice(0, 10);
|
|
459
|
+
}
|
|
460
|
+
/** Split an inclusive `[start, end]` range into consecutive non-overlapping windows of `windowDays`. */
|
|
461
|
+
function dateWindows(startDate, endDate, windowDays) {
|
|
462
|
+
const size = Math.max(1, Math.floor(windowDays));
|
|
463
|
+
const windows = [];
|
|
464
|
+
let cursor = startDate;
|
|
465
|
+
while (cursor <= endDate) {
|
|
466
|
+
const winEnd = shiftDate(cursor, size - 1);
|
|
467
|
+
const clamped = winEnd > endDate ? endDate : winEnd;
|
|
468
|
+
windows.push({
|
|
469
|
+
start: cursor,
|
|
470
|
+
end: clamped
|
|
471
|
+
});
|
|
472
|
+
cursor = shiftDate(clamped, 1);
|
|
473
|
+
}
|
|
474
|
+
return windows;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
|
|
478
|
+
* window boundary must not double up, first occurrence wins), then sorted oldest-first by date so
|
|
479
|
+
* the order is stable regardless of window seams. Id-less rows are kept and appended.
|
|
480
|
+
*/
|
|
481
|
+
function mergeWorkoutsById(pages) {
|
|
482
|
+
const byId = /* @__PURE__ */ new Map();
|
|
483
|
+
const noId = [];
|
|
484
|
+
for (const pw of pages.flat()) {
|
|
485
|
+
const id = coerceInt(pw.id);
|
|
486
|
+
if (id === null) noId.push(pw);
|
|
487
|
+
else if (!byId.has(id)) byId.set(id, pw);
|
|
488
|
+
}
|
|
489
|
+
return [...byId.values(), ...noId].sort((a, b) => {
|
|
490
|
+
const da = str(a.date) ?? "";
|
|
491
|
+
const db = str(b.date) ?? "";
|
|
492
|
+
return da < db ? -1 : da > db ? 1 : 0;
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Fetch an athlete's workouts across a long range by splitting it into windows and fetching them
|
|
497
|
+
* with bounded concurrency, then merging (deduped by workout id, sorted oldest-first). The
|
|
498
|
+
* `programworkout/range` endpoint 504s on a multi-year span, so a full-history export must chunk.
|
|
499
|
+
* `windowDays` defaults to 180; `onProgress(done, total)` reports completed windows for a progress
|
|
500
|
+
* indicator. A range that fits one window delegates to the plain fetch (API order preserved).
|
|
501
|
+
*/
|
|
502
|
+
async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}) {
|
|
503
|
+
const windows = dateWindows(startDate, endDate, opts.windowDays ?? 180);
|
|
504
|
+
if (windows.length <= 1) return fetchAthleteWorkouts(client, startDate, endDate);
|
|
505
|
+
let done = 0;
|
|
506
|
+
const total = windows.length;
|
|
507
|
+
return mergeWorkoutsById(await mapPool(windows, opts.concurrency ?? 4, async (w) => {
|
|
508
|
+
const page = await fetchAthleteWorkouts(client, w.start, w.end);
|
|
509
|
+
done += 1;
|
|
510
|
+
opts.onProgress?.(done, total);
|
|
511
|
+
return page;
|
|
512
|
+
}));
|
|
513
|
+
}
|
|
454
514
|
/**
|
|
455
515
|
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
456
516
|
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
@@ -481,66 +541,40 @@ function nonEmpty(value) {
|
|
|
481
541
|
return value !== void 0 && value !== null && String(value).trim() !== "";
|
|
482
542
|
}
|
|
483
543
|
/**
|
|
484
|
-
*
|
|
485
|
-
*
|
|
486
|
-
*
|
|
544
|
+
* Slot-indexed values for one exercise. With `requireMade`, only slots the athlete logged
|
|
545
|
+
* (`param_i_made === 1`) — the performed reader; otherwise every slot carrying data — the
|
|
546
|
+
* prescription reader. Values stay raw; the projectors format or parse them.
|
|
487
547
|
*/
|
|
488
|
-
function
|
|
489
|
-
const
|
|
548
|
+
function slotValues(ex, requireMade) {
|
|
549
|
+
const map = /* @__PURE__ */ new Map();
|
|
490
550
|
for (let i = 1; i <= 10; i += 1) {
|
|
551
|
+
if (requireMade && coerceInt(ex[`param_${i}_made`]) !== 1) continue;
|
|
491
552
|
const p1 = ex[`param_1_data_${i}`];
|
|
492
553
|
const p2 = ex[`param_2_data_${i}`];
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
else out.push(`@ ${p2}`);
|
|
554
|
+
if (!nonEmpty(p1) && !nonEmpty(p2)) continue;
|
|
555
|
+
map.set(i, {
|
|
556
|
+
p1: nonEmpty(p1) ? p1 : null,
|
|
557
|
+
p2: nonEmpty(p2) ? p2 : null
|
|
558
|
+
});
|
|
499
559
|
}
|
|
500
|
-
return
|
|
560
|
+
return map;
|
|
501
561
|
}
|
|
502
|
-
/**
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
const out = [];
|
|
511
|
-
for (let i = 1; i <= 10; i += 1) {
|
|
512
|
-
if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
|
|
513
|
-
const p1 = ex[`param_1_data_${i}`];
|
|
514
|
-
const p2 = ex[`param_2_data_${i}`];
|
|
515
|
-
const has1 = nonEmpty(p1);
|
|
516
|
-
const has2 = nonEmpty(p2);
|
|
517
|
-
if (has1 && has2) out.push(`${p1} @ ${p2}`);
|
|
518
|
-
else if (has1) out.push(String(p1));
|
|
519
|
-
else if (has2) out.push(`@ ${p2}`);
|
|
520
|
-
}
|
|
521
|
-
return out;
|
|
562
|
+
/** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
|
|
563
|
+
function fmtSlot(slot) {
|
|
564
|
+
const has1 = slot.p1 !== null;
|
|
565
|
+
const has2 = slot.p2 !== null;
|
|
566
|
+
if (has1 && has2) return `${slot.p1} @ ${slot.p2}`;
|
|
567
|
+
if (has1) return String(slot.p1);
|
|
568
|
+
if (has2) return `@ ${slot.p2}`;
|
|
569
|
+
return "";
|
|
522
570
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
return {
|
|
527
|
-
exerciseId: coerceInt(ex.exercise_id),
|
|
528
|
-
title: typeof ex.title === "string" ? ex.title : "",
|
|
529
|
-
instruction,
|
|
530
|
-
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
531
|
-
prescribed: prescribedSets(ex),
|
|
532
|
-
performed: (id !== null ? performedById.get(id) : void 0) ?? []
|
|
533
|
-
};
|
|
571
|
+
/** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
|
|
572
|
+
function prescribedStrings(ex) {
|
|
573
|
+
return [...slotValues(ex, false).values()].map(fmtSlot);
|
|
534
574
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
return
|
|
538
|
-
order: coerceInt(set.order) ?? 0,
|
|
539
|
-
title: typeof set.title === "string" && set.title !== "" ? set.title : null,
|
|
540
|
-
instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
|
|
541
|
-
isTest: coerceInt(set.is_test) === 1,
|
|
542
|
-
exercises: exercises.filter(isRecord).map((ex) => presentExercise$1(ex, performedById))
|
|
543
|
-
};
|
|
575
|
+
/** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
|
|
576
|
+
function performedStrings(ex) {
|
|
577
|
+
return [...slotValues(ex, true).values()].map(fmtSlot);
|
|
544
578
|
}
|
|
545
579
|
/** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
|
|
546
580
|
function savedSets(saved) {
|
|
@@ -559,54 +593,82 @@ function savedSets(saved) {
|
|
|
559
593
|
return out;
|
|
560
594
|
}
|
|
561
595
|
/**
|
|
562
|
-
* Map each prescription exercise id to the
|
|
563
|
-
* copy
|
|
564
|
-
* entered values live in the same `param_N_data` slots as a prescription
|
|
565
|
-
* prescription reader works on them unchanged.
|
|
596
|
+
* Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
|
|
597
|
+
* the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
|
|
598
|
+
* entered values live in the same `param_N_data` slots as a prescription.
|
|
566
599
|
*/
|
|
567
|
-
function
|
|
600
|
+
function performedSlotsByExerciseId(sets) {
|
|
568
601
|
const map = /* @__PURE__ */ new Map();
|
|
569
602
|
for (const { exercises } of sets) for (const ex of exercises) {
|
|
570
603
|
const id = coerceInt(ex.workout_set_exercise_id);
|
|
571
604
|
if (id === null) continue;
|
|
572
|
-
const
|
|
573
|
-
if (
|
|
605
|
+
const slots = slotValues(ex, true);
|
|
606
|
+
if (slots.size > 0) map.set(id, slots);
|
|
574
607
|
}
|
|
575
608
|
return map;
|
|
576
609
|
}
|
|
577
|
-
/**
|
|
578
|
-
function
|
|
610
|
+
/** Align an exercise's prescribed slots with the slots the athlete logged, per set index. */
|
|
611
|
+
function mergeExercise(prescribed, performed, meta) {
|
|
612
|
+
const indices = [.../* @__PURE__ */ new Set([...prescribed.keys(), ...performed.keys()])].sort((a, b) => a - b);
|
|
613
|
+
return {
|
|
614
|
+
...meta,
|
|
615
|
+
sets: indices.map((i) => ({
|
|
616
|
+
set: i,
|
|
617
|
+
prescribed: prescribed.get(i) ?? null,
|
|
618
|
+
performed: performed.get(i) ?? null
|
|
619
|
+
}))
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
/** A prescription block, each exercise aligned with the slots the athlete logged against it. */
|
|
623
|
+
function mergePrescriptionBlock(set, performedById) {
|
|
624
|
+
const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
|
|
625
|
+
return {
|
|
626
|
+
order: coerceInt(set.order) ?? 0,
|
|
627
|
+
title: str(set.title),
|
|
628
|
+
instruction: str(set.instruction),
|
|
629
|
+
isTest: coerceInt(set.is_test) === 1,
|
|
630
|
+
exercises: exercises.filter(isRecord).map((ex) => {
|
|
631
|
+
const id = coerceInt(ex.id);
|
|
632
|
+
const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
|
|
633
|
+
return mergeExercise(slotValues(ex, false), performed, {
|
|
634
|
+
exerciseId: coerceInt(ex.exercise_id),
|
|
635
|
+
title: typeof ex.title === "string" ? ex.title : "",
|
|
636
|
+
instruction: str(ex.instruction),
|
|
637
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type)
|
|
638
|
+
});
|
|
639
|
+
})
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
|
|
643
|
+
function mergeSavedBlock(set, exercises) {
|
|
579
644
|
return {
|
|
580
645
|
order: coerceInt(set.order) ?? 0,
|
|
581
|
-
title:
|
|
582
|
-
instruction:
|
|
646
|
+
title: str(set.title),
|
|
647
|
+
instruction: str(set.instruction),
|
|
583
648
|
isTest: coerceInt(set.is_test) === 1,
|
|
584
|
-
exercises: exercises.map((ex) => ({
|
|
649
|
+
exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
|
|
585
650
|
exerciseId: coerceInt(ex.exercise_id),
|
|
586
651
|
title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
|
|
587
|
-
instruction:
|
|
588
|
-
units: exerciseUnits(ex.param_1_type, ex.param_2_type)
|
|
589
|
-
prescribed: [],
|
|
590
|
-
performed: performedSets(ex)
|
|
652
|
+
instruction: str(ex.instruction),
|
|
653
|
+
units: exerciseUnits(ex.param_1_type, ex.param_2_type)
|
|
591
654
|
}))
|
|
592
655
|
};
|
|
593
656
|
}
|
|
594
657
|
/**
|
|
595
|
-
* Flatten one `/3.0/athlete/programworkout/range` item into
|
|
658
|
+
* Flatten one `/3.0/athlete/programworkout/range` item into the canonical merged form, joining the
|
|
596
659
|
* prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
|
|
597
|
-
* (`summarizedSavedWorkout.saved_workout`).
|
|
598
|
-
*
|
|
599
|
-
* own blocks. No `raw` is needed to see logged results.
|
|
660
|
+
* (`summarizedSavedWorkout.saved_workout`). Prescription blocks are enriched with logged slots;
|
|
661
|
+
* athlete-added / personal work with no prescription is appended as its own block.
|
|
600
662
|
*/
|
|
601
|
-
function
|
|
663
|
+
function mergeAthleteWorkout(raw) {
|
|
602
664
|
const rec = raw;
|
|
603
665
|
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
604
666
|
const workout = isRecord(ssw.workout) ? ssw.workout : {};
|
|
605
667
|
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : {};
|
|
606
668
|
const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
|
|
607
669
|
const logged = savedSets(saved);
|
|
608
|
-
const performedById =
|
|
609
|
-
const blocks = prescriptionSets.map((s) =>
|
|
670
|
+
const performedById = performedSlotsByExerciseId(logged);
|
|
671
|
+
const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById)).sort((a, b) => a.order - b.order);
|
|
610
672
|
const prescribedIds = /* @__PURE__ */ new Set();
|
|
611
673
|
for (const s of prescriptionSets) {
|
|
612
674
|
const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
@@ -618,11 +680,11 @@ function presentAthleteWorkout(raw) {
|
|
|
618
680
|
}
|
|
619
681
|
for (const { set, exercises } of logged) {
|
|
620
682
|
const extra = exercises.filter((ex) => {
|
|
621
|
-
if (
|
|
683
|
+
if (slotValues(ex, true).size === 0) return false;
|
|
622
684
|
const id = coerceInt(ex.workout_set_exercise_id);
|
|
623
685
|
return id === null || !prescribedIds.has(id);
|
|
624
686
|
});
|
|
625
|
-
if (extra.length > 0) blocks.push(
|
|
687
|
+
if (extra.length > 0) blocks.push(mergeSavedBlock(set, extra));
|
|
626
688
|
}
|
|
627
689
|
return {
|
|
628
690
|
id: coerceInt(rec.id),
|
|
@@ -631,14 +693,126 @@ function presentAthleteWorkout(raw) {
|
|
|
631
693
|
program: str(rec.program_title),
|
|
632
694
|
team: str(rec.team_title),
|
|
633
695
|
instruction: str(workout.instruction),
|
|
634
|
-
logged: blocks.some((b) => b.exercises.some((e) => e.
|
|
696
|
+
logged: blocks.some((b) => b.exercises.some((e) => e.sets.some((s) => s.performed !== null))),
|
|
635
697
|
personal: isPersonalSession(rec),
|
|
636
698
|
blocks
|
|
637
699
|
};
|
|
638
700
|
}
|
|
701
|
+
/** The per-set displays for one side (prescribed or performed), in slot order. */
|
|
702
|
+
function sideStrings(sets, pick) {
|
|
703
|
+
const out = [];
|
|
704
|
+
for (const s of sets) {
|
|
705
|
+
const slot = pick(s);
|
|
706
|
+
if (slot) out.push(fmtSlot(slot));
|
|
707
|
+
}
|
|
708
|
+
return out;
|
|
709
|
+
}
|
|
710
|
+
function toStringExercise(ex) {
|
|
711
|
+
return {
|
|
712
|
+
exerciseId: ex.exerciseId,
|
|
713
|
+
title: ex.title,
|
|
714
|
+
instruction: ex.instruction,
|
|
715
|
+
units: ex.units,
|
|
716
|
+
prescribed: sideStrings(ex.sets, (s) => s.prescribed),
|
|
717
|
+
performed: sideStrings(ex.sets, (s) => s.performed)
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
function toStringBlock(b) {
|
|
721
|
+
return {
|
|
722
|
+
order: b.order,
|
|
723
|
+
title: b.title,
|
|
724
|
+
instruction: b.instruction,
|
|
725
|
+
isTest: b.isTest,
|
|
726
|
+
exercises: b.exercises.map(toStringExercise)
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Flatten one range item into a readable workout: each exercise carries its `prescribed` and
|
|
731
|
+
* `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
|
|
732
|
+
* prescription is appended as its own blocks. No `raw` is needed to see logged results.
|
|
733
|
+
*/
|
|
734
|
+
function presentAthleteWorkout(raw) {
|
|
735
|
+
const w = mergeAthleteWorkout(raw);
|
|
736
|
+
return {
|
|
737
|
+
id: w.id,
|
|
738
|
+
date: w.date,
|
|
739
|
+
title: w.title,
|
|
740
|
+
program: w.program,
|
|
741
|
+
team: w.team,
|
|
742
|
+
instruction: w.instruction,
|
|
743
|
+
logged: w.logged,
|
|
744
|
+
personal: w.personal,
|
|
745
|
+
blocks: w.blocks.map(toStringBlock)
|
|
746
|
+
};
|
|
747
|
+
}
|
|
639
748
|
function presentAthleteWorkouts(list) {
|
|
640
749
|
return list.map(presentAthleteWorkout);
|
|
641
750
|
}
|
|
751
|
+
/** Parse a raw slot cell into an export value: a number when numeric, else the trimmed string,
|
|
752
|
+
* else null. */
|
|
753
|
+
function paramValue(v) {
|
|
754
|
+
const n = coerceNum(v);
|
|
755
|
+
if (n !== null) return n;
|
|
756
|
+
return nonEmpty(v) ? String(v).trim() : null;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Build one prescribed/performed side of a set, pulling reps/weight out of the two slots by unit.
|
|
760
|
+
* The range endpoint reports weight under the fixed `lb` param-type code regardless of the
|
|
761
|
+
* athlete's metric preference, so `lb` is the only weight unit that flows here.
|
|
762
|
+
*/
|
|
763
|
+
function exportSide(slot, units) {
|
|
764
|
+
const params = [{
|
|
765
|
+
unit: units[0] ?? null,
|
|
766
|
+
value: paramValue(slot.p1)
|
|
767
|
+
}, {
|
|
768
|
+
unit: units[1] ?? null,
|
|
769
|
+
value: paramValue(slot.p2)
|
|
770
|
+
}];
|
|
771
|
+
const repsParam = params.find((p) => p.unit === "reps");
|
|
772
|
+
const weightParam = params.find((p) => p.unit === "lb");
|
|
773
|
+
return {
|
|
774
|
+
reps: repsParam?.value ?? null,
|
|
775
|
+
weight: weightParam?.value ?? null,
|
|
776
|
+
weightUnit: weightParam?.unit ?? null,
|
|
777
|
+
params,
|
|
778
|
+
display: fmtSlot(slot)
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function toExportExercise(ex) {
|
|
782
|
+
return {
|
|
783
|
+
exerciseId: ex.exerciseId,
|
|
784
|
+
title: ex.title,
|
|
785
|
+
units: ex.units,
|
|
786
|
+
sets: ex.sets.map((s) => ({
|
|
787
|
+
set: s.set,
|
|
788
|
+
prescribed: s.prescribed ? exportSide(s.prescribed, ex.units) : null,
|
|
789
|
+
performed: s.performed ? exportSide(s.performed, ex.units) : null
|
|
790
|
+
}))
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
/** Flatten one workout into the structured export shape (numeric sets), from the same merge as
|
|
794
|
+
* {@link presentAthleteWorkout}. */
|
|
795
|
+
function presentAthleteWorkoutExport(raw) {
|
|
796
|
+
const w = mergeAthleteWorkout(raw);
|
|
797
|
+
return {
|
|
798
|
+
id: w.id,
|
|
799
|
+
date: w.date,
|
|
800
|
+
title: w.title,
|
|
801
|
+
program: w.program,
|
|
802
|
+
team: w.team,
|
|
803
|
+
logged: w.logged,
|
|
804
|
+
personal: w.personal,
|
|
805
|
+
blocks: w.blocks.map((b) => ({
|
|
806
|
+
order: b.order,
|
|
807
|
+
title: b.title,
|
|
808
|
+
isTest: b.isTest,
|
|
809
|
+
exercises: b.exercises.map(toExportExercise)
|
|
810
|
+
}))
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
function presentAthleteWorkoutsExport(list) {
|
|
814
|
+
return list.map(presentAthleteWorkoutExport);
|
|
815
|
+
}
|
|
642
816
|
/**
|
|
643
817
|
* Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
|
|
644
818
|
* every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
|
|
@@ -695,8 +869,8 @@ function presentLogTargets(list) {
|
|
|
695
869
|
savedWorkoutSetExerciseId: id,
|
|
696
870
|
title: exerciseTitle(ex),
|
|
697
871
|
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
698
|
-
prescribed:
|
|
699
|
-
performed:
|
|
872
|
+
prescribed: prescribedStrings(ex),
|
|
873
|
+
performed: performedStrings(ex)
|
|
700
874
|
};
|
|
701
875
|
}).filter((e) => e !== null);
|
|
702
876
|
targets.push({
|
|
@@ -715,10 +889,11 @@ function presentLogTargets(list) {
|
|
|
715
889
|
return targets;
|
|
716
890
|
}
|
|
717
891
|
/**
|
|
718
|
-
* Narrow a
|
|
719
|
-
*
|
|
720
|
-
*
|
|
721
|
-
*
|
|
892
|
+
* Narrow a workout list for the common "what did I actually do" reads. `loggedOnly` keeps only
|
|
893
|
+
* workouts the athlete logged a set on (the reliable signal, not the API's completion flag).
|
|
894
|
+
* `limit` keeps the most recent N by date (newest first). Both are pure post-filters; the raw API
|
|
895
|
+
* path is left untouched. Generic over the presented (`AthleteWorkoutView`) and exported
|
|
896
|
+
* (`WorkoutHistoryExport`) shapes, which both carry `date` and `logged`, so one rule serves both.
|
|
722
897
|
*/
|
|
723
898
|
function selectWorkouts(list, opts = {}) {
|
|
724
899
|
let out = opts.loggedOnly === true ? list.filter((w) => w.logged) : [...list];
|
|
@@ -1464,6 +1639,132 @@ async function logSessionForAthlete(client, args) {
|
|
|
1464
1639
|
};
|
|
1465
1640
|
}
|
|
1466
1641
|
//#endregion
|
|
1642
|
+
//#region src/workout-export.ts
|
|
1643
|
+
const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
|
|
1644
|
+
/** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
|
|
1645
|
+
function workoutsToJson(workouts) {
|
|
1646
|
+
return JSON.stringify(workouts, null, 2);
|
|
1647
|
+
}
|
|
1648
|
+
const CSV_HEADER = [
|
|
1649
|
+
"date",
|
|
1650
|
+
"program",
|
|
1651
|
+
"team",
|
|
1652
|
+
"workout",
|
|
1653
|
+
"block",
|
|
1654
|
+
"exercise",
|
|
1655
|
+
"set",
|
|
1656
|
+
"prescribed_reps",
|
|
1657
|
+
"prescribed_weight",
|
|
1658
|
+
"performed_reps",
|
|
1659
|
+
"performed_weight",
|
|
1660
|
+
"weight_unit",
|
|
1661
|
+
"prescribed",
|
|
1662
|
+
"performed"
|
|
1663
|
+
];
|
|
1664
|
+
/**
|
|
1665
|
+
* Format a CSV cell. Numbers pass through verbatim. For strings: neutralize spreadsheet formula
|
|
1666
|
+
* injection first — a text cell that opens with `=`, `+`, `-`, `@`, tab, or CR is prefixed with a
|
|
1667
|
+
* single quote so Excel/Sheets treat a coach-authored title like `=HYPERLINK(...)` as text, not a
|
|
1668
|
+
* formula — then quote (and double internal quotes) when the value holds a comma, quote, or newline.
|
|
1669
|
+
*/
|
|
1670
|
+
function csvCell(value) {
|
|
1671
|
+
if (value === null || value === void 0) return "";
|
|
1672
|
+
if (typeof value === "number") return String(value);
|
|
1673
|
+
const guarded = /^[=+\-@\t\r]/u.test(value) ? `'${value}` : value;
|
|
1674
|
+
return /["\n\r,]/u.test(guarded) ? `"${guarded.replace(/"/gu, "\"\"")}"` : guarded;
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* One row per set. `reps`/`weight` columns hold the broken-out numeric values for the common
|
|
1678
|
+
* lifting case; the trailing `prescribed`/`performed` columns hold the raw `"p1 @ p2"` display so a
|
|
1679
|
+
* time, distance, or percentage exercise (where the reps/weight columns are blank) loses nothing.
|
|
1680
|
+
*/
|
|
1681
|
+
function workoutsToCsv(workouts) {
|
|
1682
|
+
const rows = [CSV_HEADER.join(",")];
|
|
1683
|
+
for (const w of workouts) for (const block of w.blocks) for (const ex of block.exercises) for (const set of ex.sets) {
|
|
1684
|
+
const p = set.prescribed;
|
|
1685
|
+
const q = set.performed;
|
|
1686
|
+
rows.push([
|
|
1687
|
+
w.date,
|
|
1688
|
+
w.program,
|
|
1689
|
+
w.team,
|
|
1690
|
+
w.title,
|
|
1691
|
+
block.title,
|
|
1692
|
+
ex.title,
|
|
1693
|
+
set.set,
|
|
1694
|
+
p?.reps,
|
|
1695
|
+
p?.weight,
|
|
1696
|
+
q?.reps,
|
|
1697
|
+
q?.weight,
|
|
1698
|
+
q?.weightUnit ?? p?.weightUnit,
|
|
1699
|
+
p?.display,
|
|
1700
|
+
q?.display
|
|
1701
|
+
].map(csvCell).join(","));
|
|
1702
|
+
}
|
|
1703
|
+
return `${rows.join("\r\n")}\r\n`;
|
|
1704
|
+
}
|
|
1705
|
+
/** The set of unit labels an exercise uses, e.g. `"reps, lb"`. */
|
|
1706
|
+
function unitsLabel(units) {
|
|
1707
|
+
const named = units.filter((u) => u !== null);
|
|
1708
|
+
return named.length > 0 ? ` (${named.join(", ")})` : "";
|
|
1709
|
+
}
|
|
1710
|
+
function sideText(side) {
|
|
1711
|
+
return side && side.display !== "" ? side.display : "—";
|
|
1712
|
+
}
|
|
1713
|
+
/** A readable, indented rendering — one athlete-friendly block of text per session. */
|
|
1714
|
+
function workoutsToText(workouts) {
|
|
1715
|
+
const lines = [
|
|
1716
|
+
"# TrainHeroic workout history",
|
|
1717
|
+
`# ${`${workouts.length} session${workouts.length === 1 ? "" : "s"}`}`,
|
|
1718
|
+
""
|
|
1719
|
+
];
|
|
1720
|
+
for (const w of workouts) {
|
|
1721
|
+
lines.push(`${w.date} ${w.title || "(untitled)"}`);
|
|
1722
|
+
const scope = [w.program && `Program: ${w.program}`, w.team && `Team: ${w.team}`].filter(Boolean);
|
|
1723
|
+
if (scope.length > 0) lines.push(scope.join(" · "));
|
|
1724
|
+
if (w.personal) lines.push("(personal session)");
|
|
1725
|
+
for (const block of w.blocks) {
|
|
1726
|
+
if (block.exercises.length === 0) continue;
|
|
1727
|
+
if (block.title) lines.push(` ${block.title}`);
|
|
1728
|
+
for (const ex of block.exercises) {
|
|
1729
|
+
lines.push(` ${ex.title || "(exercise)"}${unitsLabel(ex.units)}`);
|
|
1730
|
+
for (const set of ex.sets) {
|
|
1731
|
+
const done = sideText(set.performed);
|
|
1732
|
+
const planned = set.prescribed ? ` (planned ${sideText(set.prescribed)})` : "";
|
|
1733
|
+
lines.push(` set ${set.set} ${done}${planned}`);
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
lines.push("");
|
|
1738
|
+
}
|
|
1739
|
+
return lines.join("\n");
|
|
1740
|
+
}
|
|
1741
|
+
const FORMAT_META = {
|
|
1742
|
+
json: {
|
|
1743
|
+
contentType: "application/json",
|
|
1744
|
+
extension: "json"
|
|
1745
|
+
},
|
|
1746
|
+
csv: {
|
|
1747
|
+
contentType: "text/csv",
|
|
1748
|
+
extension: "csv"
|
|
1749
|
+
},
|
|
1750
|
+
text: {
|
|
1751
|
+
contentType: "text/plain",
|
|
1752
|
+
extension: "txt"
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
/** Serialize the workout history to the chosen format, with content-type and a suggested filename. */
|
|
1756
|
+
function serializeWorkoutHistory(workouts, format, opts = {}) {
|
|
1757
|
+
const meta = FORMAT_META[format];
|
|
1758
|
+
const content = format === "json" ? workoutsToJson(workouts) : format === "csv" ? workoutsToCsv(workouts) : workoutsToText(workouts);
|
|
1759
|
+
const base = opts.filenameBase ?? DEFAULT_FILENAME_BASE;
|
|
1760
|
+
return {
|
|
1761
|
+
content,
|
|
1762
|
+
contentType: meta.contentType,
|
|
1763
|
+
extension: meta.extension,
|
|
1764
|
+
filename: `${base}.${meta.extension}`
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
//#endregion
|
|
1467
1768
|
//#region src/coach.ts
|
|
1468
1769
|
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
1469
1770
|
/** Normalize one-or-many emails into a deduped, trimmed list. */
|
|
@@ -2569,4 +2870,4 @@ var ExerciseLibrary = class {
|
|
|
2569
2870
|
}
|
|
2570
2871
|
};
|
|
2571
2872
|
//#endregion
|
|
2572
|
-
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
2873
|
+
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
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.7.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.0.1",
|