@trainheroic-unofficial/js 1.4.0 → 1.6.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 +1 -1
- package/dist/index.d.mts +71 -7
- package/dist/index.mjs +229 -91
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @trainheroic-unofficial/js
|
|
2
2
|
|
|
3
|
-
An unofficial TypeScript SDK for the TrainHeroic
|
|
3
|
+
An unofficial TypeScript SDK for the TrainHeroic API. The client covers auth and
|
|
4
4
|
session renewal across both TrainHeroic hosts, a searchable exercise library, workout
|
|
5
5
|
encoding, and messaging. It runs in any modern JavaScript runtime, including Cloudflare
|
|
6
6
|
workerd.
|
package/dist/index.d.mts
CHANGED
|
@@ -66,6 +66,9 @@ declare const PARAM_WEIGHT = 1;
|
|
|
66
66
|
declare const PARAM_PCT_MAX = 2;
|
|
67
67
|
declare const PARAM_REPS = 3;
|
|
68
68
|
declare const PARAM_RPE = 14;
|
|
69
|
+
/** TrainHeroic stores up to 10 sets per exercise as `param_N_data_1..10`. One source of truth for
|
|
70
|
+
* the bound, shared by the workout presenters and the set-logging write path. */
|
|
71
|
+
declare const MAX_PARAM_SLOTS = 10;
|
|
69
72
|
declare function coerceInt(value: unknown): number | null;
|
|
70
73
|
declare function coerceNum(value: unknown): number | null;
|
|
71
74
|
declare function unitLabel(paramType: unknown): string | null;
|
|
@@ -88,6 +91,20 @@ declare function unwrapEnvelope(body: unknown): unknown;
|
|
|
88
91
|
/** Pull the exercise array out of whatever shape the bulk endpoint returns. */
|
|
89
92
|
declare function asExerciseList(body: unknown): Array<Record<string, unknown>>;
|
|
90
93
|
declare function isRecord(x: unknown): x is Record<string, unknown>;
|
|
94
|
+
/** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
|
|
95
|
+
declare function str(v: unknown): string | null;
|
|
96
|
+
/**
|
|
97
|
+
* The display title of a saved-copy exercise row, preferring `exercise_title`, then `title`, then
|
|
98
|
+
* the given fallback. The saved-workout shape carries the title under either key depending on the
|
|
99
|
+
* endpoint, so this is the one place that reconciles them.
|
|
100
|
+
*/
|
|
101
|
+
declare function exerciseTitle(ex: Record<string, unknown>, fallback?: string): string;
|
|
102
|
+
/**
|
|
103
|
+
* True when a program-workout range item is a personal (athlete-created) session rather than a
|
|
104
|
+
* coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
|
|
105
|
+
* definition every consumer (presenter, find-or-create, the remove guard) reads through.
|
|
106
|
+
*/
|
|
107
|
+
declare function isPersonalSession(pw: unknown): boolean;
|
|
91
108
|
/**
|
|
92
109
|
* Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
|
|
93
110
|
* exact title, then prefix, then count of matched tokens, with shorter titles and
|
|
@@ -252,16 +269,22 @@ declare function summarizeAthleteWorkouts(list: readonly AthleteWorkoutView[]):
|
|
|
252
269
|
* specific lift's PRs.
|
|
253
270
|
*/
|
|
254
271
|
declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId: number, year: number, month: number): CoachAthleteTraining;
|
|
272
|
+
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
273
|
+
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region src/athlete-set-write.d.ts
|
|
255
276
|
/**
|
|
256
277
|
* One set of entered values for a single exercise within a saved workout set.
|
|
257
278
|
* `param1` and `param2` correspond to the exercise's first and second parameter types
|
|
258
|
-
* (e.g. reps and weight).
|
|
279
|
+
* (e.g. reps and weight). Optional `slot` is the 1-based prescribed position this set fills;
|
|
280
|
+
* omit it and the sets fill positions sequentially from the first. At most 10 sets are supported.
|
|
259
281
|
*/
|
|
260
282
|
type SetResult = {
|
|
261
283
|
savedWorkoutSetExerciseId: number;
|
|
262
284
|
sets: Array<{
|
|
263
285
|
param1?: number | string;
|
|
264
286
|
param2?: number | string;
|
|
287
|
+
slot?: number;
|
|
265
288
|
}>;
|
|
266
289
|
};
|
|
267
290
|
/**
|
|
@@ -282,6 +305,7 @@ declare function toSetResults(results: ReadonlyArray<{
|
|
|
282
305
|
sets: ReadonlyArray<{
|
|
283
306
|
param1?: number | string | undefined;
|
|
284
307
|
param2?: number | string | undefined;
|
|
308
|
+
slot?: number | undefined;
|
|
285
309
|
}>;
|
|
286
310
|
}>): SetResult[];
|
|
287
311
|
/**
|
|
@@ -291,20 +315,31 @@ declare function toSetResults(results: ReadonlyArray<{
|
|
|
291
315
|
*
|
|
292
316
|
* `mode` selects which write this is — the same endpoint serves both:
|
|
293
317
|
* - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
|
|
294
|
-
* and the exercise `completed` flag is 1 when any set has data.
|
|
318
|
+
* and the exercise `completed` flag is 1 when any set has logged data.
|
|
295
319
|
* - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
|
|
296
320
|
* `completed` left at 0 so the set is not marked done. This matches what the app sends when a
|
|
297
321
|
* coach edits an athlete's prescribed reps/weight.
|
|
298
322
|
*
|
|
323
|
+
* Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
|
|
324
|
+
* when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
|
|
325
|
+
* it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
|
|
326
|
+
* a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
|
|
327
|
+
* (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
|
|
328
|
+
* the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
|
|
329
|
+
* sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
|
|
330
|
+
* copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
|
|
331
|
+
*
|
|
299
332
|
* Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
|
|
300
|
-
* required from the live exercise record; everything else is derived from `results
|
|
333
|
+
* required from the live exercise record; everything else is derived from `results` and the
|
|
334
|
+
* preserved slots of `existing`.
|
|
301
335
|
*
|
|
302
336
|
* Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
|
|
303
337
|
*/
|
|
304
338
|
declare function buildExerciseSetPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly {
|
|
305
339
|
param1?: number | string;
|
|
306
340
|
param2?: number | string;
|
|
307
|
-
|
|
341
|
+
slot?: number;
|
|
342
|
+
}[], mode: SetWriteMode, existing?: Record<string, unknown>): Record<string, unknown>;
|
|
308
343
|
/**
|
|
309
344
|
* Locate the target saved workout set across all program workouts on the given day.
|
|
310
345
|
* Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
|
|
@@ -356,6 +391,7 @@ declare function logAthleteSet(client: TrainHeroicClient, args: {
|
|
|
356
391
|
}): Promise<{
|
|
357
392
|
savedWorkoutSetId: number;
|
|
358
393
|
exercisesLogged: number;
|
|
394
|
+
setCompleted: boolean;
|
|
359
395
|
}>;
|
|
360
396
|
/**
|
|
361
397
|
* Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
|
|
@@ -375,6 +411,7 @@ declare function logForAthlete(client: TrainHeroicClient, args: {
|
|
|
375
411
|
}): Promise<{
|
|
376
412
|
savedWorkoutSetId: number;
|
|
377
413
|
exercisesLogged: number;
|
|
414
|
+
setCompleted: boolean;
|
|
378
415
|
}>;
|
|
379
416
|
/**
|
|
380
417
|
* Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
|
|
@@ -456,6 +493,18 @@ type AddedExercise = {
|
|
|
456
493
|
* logAthleteSet.
|
|
457
494
|
*/
|
|
458
495
|
declare function addExercisesToWorkout(client: TrainHeroicClient, workoutId: number, exercises: AddedExercise[]): Promise<unknown>;
|
|
496
|
+
/**
|
|
497
|
+
* DELETE /v5/programWorkouts/{programWorkoutId} — remove a personal (athlete-created) workout
|
|
498
|
+
* session from the athlete's own calendar. Re-reads the day and removes ONLY a personal session
|
|
499
|
+
* (`personal_cal`): it throws if no workout with that id is on the date, or if the target is a
|
|
500
|
+
* coach-scheduled workout (which is not the athlete's to delete). This guard lives here, at the
|
|
501
|
+
* delete itself, so no caller can issue the DELETE against a coach workout by skipping a check.
|
|
502
|
+
* Throws on a non-ok response.
|
|
503
|
+
*/
|
|
504
|
+
declare function removePersonalWorkout(client: TrainHeroicClient, args: {
|
|
505
|
+
programWorkoutId: number;
|
|
506
|
+
date: string;
|
|
507
|
+
}): Promise<void>;
|
|
459
508
|
/** One exercise's entered sets, keyed by the exercise id rather than a saved-set id. */
|
|
460
509
|
type SessionExercise = {
|
|
461
510
|
exerciseId: number;
|
|
@@ -465,6 +514,16 @@ type SessionExercise = {
|
|
|
465
514
|
param2?: number | string;
|
|
466
515
|
}>;
|
|
467
516
|
};
|
|
517
|
+
/** A coach-scheduled prescription on the same day that matches an exercise the athlete just logged
|
|
518
|
+
* ad-hoc. Surfaced as a hint that {@link logAthleteSet} could log into the scheduled workout. */
|
|
519
|
+
type ScheduledAlternative = {
|
|
520
|
+
exerciseId: number;
|
|
521
|
+
title: string;
|
|
522
|
+
program: string | null;
|
|
523
|
+
workoutTitle: string;
|
|
524
|
+
savedWorkoutSetId: number;
|
|
525
|
+
savedWorkoutSetExerciseId: number;
|
|
526
|
+
};
|
|
468
527
|
/** Result of logging a session by exercise: which sets were written, and (athlete) whether a
|
|
469
528
|
* new personal session had to be created for the date. */
|
|
470
529
|
type LogSessionResult = {
|
|
@@ -474,6 +533,13 @@ type LogSessionResult = {
|
|
|
474
533
|
savedWorkoutSetId: number;
|
|
475
534
|
exercisesLogged: number;
|
|
476
535
|
}>;
|
|
536
|
+
/**
|
|
537
|
+
* Coach-scheduled prescriptions that day matching a logged exercise (athlete path only). Present
|
|
538
|
+
* only when non-empty — a hint that the same lift was already on the athlete's scheduled workout,
|
|
539
|
+
* so {@link logAthleteSet} (athlete_log_set) could have logged into it instead of a personal
|
|
540
|
+
* session. The ad-hoc log still happened; this does not redirect it.
|
|
541
|
+
*/
|
|
542
|
+
scheduledAlternatives?: ScheduledAlternative[];
|
|
477
543
|
};
|
|
478
544
|
/**
|
|
479
545
|
* Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
|
|
@@ -498,8 +564,6 @@ declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
|
498
564
|
date: string;
|
|
499
565
|
exercises: readonly SessionExercise[];
|
|
500
566
|
}): Promise<LogSessionResult>;
|
|
501
|
-
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
502
|
-
declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
503
567
|
//#endregion
|
|
504
568
|
//#region src/main-lifts.d.ts
|
|
505
569
|
type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
|
|
@@ -775,4 +839,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
775
839
|
stats(): Promise<Record<string, unknown>>;
|
|
776
840
|
}
|
|
777
841
|
//#endregion
|
|
778
|
-
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, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, 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, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -177,6 +177,9 @@ const PARAM_WEIGHT = 1;
|
|
|
177
177
|
const PARAM_PCT_MAX = 2;
|
|
178
178
|
const PARAM_REPS = 3;
|
|
179
179
|
const PARAM_RPE = 14;
|
|
180
|
+
/** TrainHeroic stores up to 10 sets per exercise as `param_N_data_1..10`. One source of truth for
|
|
181
|
+
* the bound, shared by the workout presenters and the set-logging write path. */
|
|
182
|
+
const MAX_PARAM_SLOTS = 10;
|
|
180
183
|
function coerceInt(value) {
|
|
181
184
|
if (typeof value === "boolean") return value ? 1 : 0;
|
|
182
185
|
if (typeof value === "number") return Number.isFinite(value) ? Math.trunc(value) : null;
|
|
@@ -270,6 +273,26 @@ function asExerciseList(body) {
|
|
|
270
273
|
function isRecord(x) {
|
|
271
274
|
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
272
275
|
}
|
|
276
|
+
/** A non-empty string, or null. Narrows a loosely-typed API field to a usable string. */
|
|
277
|
+
function str(v) {
|
|
278
|
+
return typeof v === "string" && v !== "" ? v : null;
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The display title of a saved-copy exercise row, preferring `exercise_title`, then `title`, then
|
|
282
|
+
* the given fallback. The saved-workout shape carries the title under either key depending on the
|
|
283
|
+
* endpoint, so this is the one place that reconciles them.
|
|
284
|
+
*/
|
|
285
|
+
function exerciseTitle(ex, fallback = "") {
|
|
286
|
+
return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* True when a program-workout range item is a personal (athlete-created) session rather than a
|
|
290
|
+
* coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
|
|
291
|
+
* definition every consumer (presenter, find-or-create, the remove guard) reads through.
|
|
292
|
+
*/
|
|
293
|
+
function isPersonalSession(pw) {
|
|
294
|
+
return isRecord(pw) && pw.personal_cal === true;
|
|
295
|
+
}
|
|
273
296
|
/**
|
|
274
297
|
* Rank candidate rows for a free-text query (FTS5 replacement). Higher is better:
|
|
275
298
|
* exact title, then prefix, then count of matched tokens, with shorter titles and
|
|
@@ -454,7 +477,6 @@ function fetchLeaderboard(client, workoutId, opts = {}) {
|
|
|
454
477
|
const query = qs.toString();
|
|
455
478
|
return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
|
|
456
479
|
}
|
|
457
|
-
const SLOTS = 10;
|
|
458
480
|
function nonEmpty(value) {
|
|
459
481
|
return value !== void 0 && value !== null && String(value).trim() !== "";
|
|
460
482
|
}
|
|
@@ -465,7 +487,7 @@ function nonEmpty(value) {
|
|
|
465
487
|
*/
|
|
466
488
|
function prescribedSets(ex) {
|
|
467
489
|
const out = [];
|
|
468
|
-
for (let i = 1; i <=
|
|
490
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
469
491
|
const p1 = ex[`param_1_data_${i}`];
|
|
470
492
|
const p2 = ex[`param_2_data_${i}`];
|
|
471
493
|
const has1 = nonEmpty(p1);
|
|
@@ -486,7 +508,7 @@ function prescribedSets(ex) {
|
|
|
486
508
|
*/
|
|
487
509
|
function performedSets(ex) {
|
|
488
510
|
const out = [];
|
|
489
|
-
for (let i = 1; i <=
|
|
511
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
490
512
|
if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
|
|
491
513
|
const p1 = ex[`param_1_data_${i}`];
|
|
492
514
|
const p2 = ex[`param_2_data_${i}`];
|
|
@@ -520,9 +542,6 @@ function presentBlock(set, performedById) {
|
|
|
520
542
|
exercises: exercises.filter(isRecord).map((ex) => presentExercise$1(ex, performedById))
|
|
521
543
|
};
|
|
522
544
|
}
|
|
523
|
-
function str$1(v) {
|
|
524
|
-
return typeof v === "string" && v !== "" ? v : null;
|
|
525
|
-
}
|
|
526
545
|
/** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
|
|
527
546
|
function savedSets(saved) {
|
|
528
547
|
const out = [];
|
|
@@ -607,12 +626,13 @@ function presentAthleteWorkout(raw) {
|
|
|
607
626
|
}
|
|
608
627
|
return {
|
|
609
628
|
id: coerceInt(rec.id),
|
|
610
|
-
date: str
|
|
611
|
-
title: str
|
|
612
|
-
program: str
|
|
613
|
-
team: str
|
|
614
|
-
instruction: str
|
|
629
|
+
date: str(rec.date) ?? "",
|
|
630
|
+
title: str(rec.workout_title) ?? "",
|
|
631
|
+
program: str(rec.program_title),
|
|
632
|
+
team: str(rec.team_title),
|
|
633
|
+
instruction: str(workout.instruction),
|
|
615
634
|
logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
|
|
635
|
+
personal: isPersonalSession(rec),
|
|
616
636
|
blocks
|
|
617
637
|
};
|
|
618
638
|
}
|
|
@@ -636,7 +656,7 @@ function selectWorkoutsByProgram(list, filter) {
|
|
|
636
656
|
if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
|
|
637
657
|
if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
|
|
638
658
|
if (needle) {
|
|
639
|
-
if (`${str
|
|
659
|
+
if (`${str(rec.program_title) ?? ""} ${str(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
|
|
640
660
|
}
|
|
641
661
|
return false;
|
|
642
662
|
});
|
|
@@ -657,11 +677,11 @@ function presentLogTargets(list) {
|
|
|
657
677
|
const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
|
|
658
678
|
const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
|
|
659
679
|
if (!saved) continue;
|
|
660
|
-
const date = str
|
|
661
|
-
const workoutTitle = str
|
|
662
|
-
const program = str
|
|
680
|
+
const date = str(rec.date) ?? "";
|
|
681
|
+
const workoutTitle = str(rec.workout_title) ?? "";
|
|
682
|
+
const program = str(rec.program_title);
|
|
663
683
|
const programId = coerceInt(rec.program_id);
|
|
664
|
-
const team = str
|
|
684
|
+
const team = str(rec.team_title);
|
|
665
685
|
const teamId = coerceInt(rec.team_id);
|
|
666
686
|
const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
|
|
667
687
|
for (const s of sets) {
|
|
@@ -673,7 +693,7 @@ function presentLogTargets(list) {
|
|
|
673
693
|
if (id === null) return null;
|
|
674
694
|
return {
|
|
675
695
|
savedWorkoutSetExerciseId: id,
|
|
676
|
-
title:
|
|
696
|
+
title: exerciseTitle(ex),
|
|
677
697
|
units: exerciseUnits(ex.param_1_type, ex.param_2_type),
|
|
678
698
|
prescribed: prescribedSets(ex),
|
|
679
699
|
performed: performedSets(ex)
|
|
@@ -687,7 +707,7 @@ function presentLogTargets(list) {
|
|
|
687
707
|
team,
|
|
688
708
|
teamId,
|
|
689
709
|
savedWorkoutSetId,
|
|
690
|
-
setTitle: str
|
|
710
|
+
setTitle: str(s.title),
|
|
691
711
|
exercises
|
|
692
712
|
});
|
|
693
713
|
}
|
|
@@ -722,6 +742,7 @@ function summarizeAthleteWorkouts(list) {
|
|
|
722
742
|
program: w.program,
|
|
723
743
|
team: w.team,
|
|
724
744
|
logged: w.logged,
|
|
745
|
+
personal: w.personal,
|
|
725
746
|
exerciseCount,
|
|
726
747
|
performedCount
|
|
727
748
|
};
|
|
@@ -775,7 +796,29 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
|
|
|
775
796
|
sessions
|
|
776
797
|
};
|
|
777
798
|
}
|
|
778
|
-
|
|
799
|
+
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
800
|
+
function presentExerciseHistory(detail) {
|
|
801
|
+
return {
|
|
802
|
+
liftPRs: (detail.liftPRs ?? []).map((p) => ({
|
|
803
|
+
description: p.description ?? null,
|
|
804
|
+
reps: p.reps ?? null,
|
|
805
|
+
weight: p.weight ?? null,
|
|
806
|
+
units: p.units ?? null,
|
|
807
|
+
date: p.dateCompleted ?? null
|
|
808
|
+
})),
|
|
809
|
+
sessions: (detail.history ?? []).map((h) => ({
|
|
810
|
+
date: h.dateCompleted,
|
|
811
|
+
abr: h.abr ?? null,
|
|
812
|
+
estimated1RM: h.bestEstimated1RM ?? null,
|
|
813
|
+
sets: (h.sets ?? []).map((s) => ({
|
|
814
|
+
setNumber: s.setNumber,
|
|
815
|
+
value: s.formattedValue ?? null
|
|
816
|
+
}))
|
|
817
|
+
}))
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
//#endregion
|
|
821
|
+
//#region src/athlete-set-write.ts
|
|
779
822
|
/**
|
|
780
823
|
* Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
|
|
781
824
|
* {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
|
|
@@ -790,10 +833,11 @@ function toSetResults(results) {
|
|
|
790
833
|
return {
|
|
791
834
|
savedWorkoutSetExerciseId: id,
|
|
792
835
|
sets: r.sets.map((s) => {
|
|
793
|
-
const
|
|
794
|
-
if (s.param1 !== void 0)
|
|
795
|
-
if (s.param2 !== void 0)
|
|
796
|
-
|
|
836
|
+
const set = {};
|
|
837
|
+
if (s.param1 !== void 0) set.param1 = s.param1;
|
|
838
|
+
if (s.param2 !== void 0) set.param2 = s.param2;
|
|
839
|
+
if (s.slot !== void 0) set.slot = s.slot;
|
|
840
|
+
return set;
|
|
797
841
|
})
|
|
798
842
|
};
|
|
799
843
|
});
|
|
@@ -805,36 +849,96 @@ function toSetResults(results) {
|
|
|
805
849
|
*
|
|
806
850
|
* `mode` selects which write this is — the same endpoint serves both:
|
|
807
851
|
* - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
|
|
808
|
-
* and the exercise `completed` flag is 1 when any set has data.
|
|
852
|
+
* and the exercise `completed` flag is 1 when any set has logged data.
|
|
809
853
|
* - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
|
|
810
854
|
* `completed` left at 0 so the set is not marked done. This matches what the app sends when a
|
|
811
855
|
* coach edits an athlete's prescribed reps/weight.
|
|
812
856
|
*
|
|
857
|
+
* Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
|
|
858
|
+
* when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
|
|
859
|
+
* it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
|
|
860
|
+
* a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
|
|
861
|
+
* (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
|
|
862
|
+
* the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
|
|
863
|
+
* sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
|
|
864
|
+
* copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
|
|
865
|
+
*
|
|
813
866
|
* Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
|
|
814
|
-
* required from the live exercise record; everything else is derived from `results
|
|
867
|
+
* required from the live exercise record; everything else is derived from `results` and the
|
|
868
|
+
* preserved slots of `existing`.
|
|
815
869
|
*
|
|
816
870
|
* Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
|
|
817
871
|
*/
|
|
818
|
-
function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
|
|
819
|
-
if (results.length >
|
|
872
|
+
function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
|
|
873
|
+
if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
|
|
874
|
+
const bySlot = /* @__PURE__ */ new Map();
|
|
875
|
+
results.forEach((set, i) => {
|
|
876
|
+
const slot = set.slot ?? i + 1;
|
|
877
|
+
if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
|
|
878
|
+
if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
|
|
879
|
+
bySlot.set(slot, set);
|
|
880
|
+
});
|
|
820
881
|
const performed = mode === "log";
|
|
821
|
-
const
|
|
882
|
+
const carryOver = performed && existing !== void 0;
|
|
822
883
|
const body = {
|
|
823
884
|
id: savedWorkoutSetExerciseId,
|
|
824
885
|
saved_workout_set_id: savedWorkoutSetId,
|
|
825
|
-
workout_set_exercise_id: workoutSetExerciseId
|
|
826
|
-
completed: performed && hasData ? 1 : 0
|
|
886
|
+
workout_set_exercise_id: workoutSetExerciseId
|
|
827
887
|
};
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
|
|
888
|
+
let anyMade = false;
|
|
889
|
+
for (let i = 1; i <= 10; i += 1) {
|
|
890
|
+
const target = bySlot.get(i);
|
|
891
|
+
let p1;
|
|
892
|
+
let p2;
|
|
893
|
+
let made;
|
|
894
|
+
if (target) {
|
|
895
|
+
p1 = target.param1 !== void 0 ? String(target.param1) : "";
|
|
896
|
+
p2 = target.param2 !== void 0 ? String(target.param2) : "";
|
|
897
|
+
made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
|
|
898
|
+
} else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
|
|
899
|
+
p1 = existingSlotData(existing, `param_1_data_${i}`);
|
|
900
|
+
p2 = existingSlotData(existing, `param_2_data_${i}`);
|
|
901
|
+
made = 1;
|
|
902
|
+
} else {
|
|
903
|
+
p1 = "";
|
|
904
|
+
p2 = "";
|
|
905
|
+
made = 0;
|
|
906
|
+
}
|
|
907
|
+
if (made === 1) anyMade = true;
|
|
908
|
+
body[`param_${i}_made`] = made;
|
|
833
909
|
body[`param_1_data_${i}`] = p1;
|
|
834
910
|
body[`param_2_data_${i}`] = p2;
|
|
835
911
|
}
|
|
912
|
+
body.completed = performed && anyMade ? 1 : 0;
|
|
836
913
|
return body;
|
|
837
914
|
}
|
|
915
|
+
/** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
|
|
916
|
+
function existingSlotData(existing, key) {
|
|
917
|
+
const v = existing?.[key];
|
|
918
|
+
return v === void 0 || v === null ? "" : String(v);
|
|
919
|
+
}
|
|
920
|
+
/** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
|
|
921
|
+
function exerciseHasLoggedData(ex) {
|
|
922
|
+
for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
|
|
923
|
+
return false;
|
|
924
|
+
}
|
|
925
|
+
/** True when a result carries at least one non-empty param value (so it produces a performed slot). */
|
|
926
|
+
function resultHasData(result) {
|
|
927
|
+
return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Whether every exercise in a saved workout set now has logged data — either written with data in
|
|
931
|
+
* this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
|
|
932
|
+
* superset/circuit stays open until the last exercise is logged, so completing it on a partial log
|
|
933
|
+
* does not flip its still-empty siblings to "done". An exercise written with only empty values does
|
|
934
|
+
* not count (it would not be marked performed), so an all-empty log never completes the set.
|
|
935
|
+
*/
|
|
936
|
+
function isSetFullyLogged(exercises, loggedIds) {
|
|
937
|
+
return exercises.every((ex) => {
|
|
938
|
+
const id = coerceInt(ex.id);
|
|
939
|
+
return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
|
|
940
|
+
});
|
|
941
|
+
}
|
|
838
942
|
/**
|
|
839
943
|
* Locate the target saved workout set across all program workouts on the given day.
|
|
840
944
|
* Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
|
|
@@ -865,8 +969,7 @@ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
|
|
|
865
969
|
if (setId !== null) {
|
|
866
970
|
const exLabels = exercises.map((ex) => {
|
|
867
971
|
const exId = coerceInt(ex.id);
|
|
868
|
-
|
|
869
|
-
return exId === null ? null : `${exId} (${title})`;
|
|
972
|
+
return exId === null ? null : `${exId} (${exerciseTitle(ex, "exercise")})`;
|
|
870
973
|
}).filter((x) => x !== null);
|
|
871
974
|
available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
|
|
872
975
|
}
|
|
@@ -933,7 +1036,8 @@ async function logAthleteSet(client, args) {
|
|
|
933
1036
|
const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
|
|
934
1037
|
return {
|
|
935
1038
|
savedWorkoutSetId: r.savedWorkoutSetId,
|
|
936
|
-
exercisesLogged: r.exercisesWritten
|
|
1039
|
+
exercisesLogged: r.exercisesWritten,
|
|
1040
|
+
setCompleted: r.setCompleted
|
|
937
1041
|
};
|
|
938
1042
|
}
|
|
939
1043
|
/**
|
|
@@ -954,7 +1058,8 @@ async function logForAthlete(client, args) {
|
|
|
954
1058
|
}, workouts, args.savedWorkoutSetId, args.results, "log");
|
|
955
1059
|
return {
|
|
956
1060
|
savedWorkoutSetId: r.savedWorkoutSetId,
|
|
957
|
-
exercisesLogged: r.exercisesWritten
|
|
1061
|
+
exercisesLogged: r.exercisesWritten,
|
|
1062
|
+
setCompleted: r.setCompleted
|
|
958
1063
|
};
|
|
959
1064
|
}
|
|
960
1065
|
/**
|
|
@@ -1015,7 +1120,7 @@ async function swapAthleteExercise(client, args) {
|
|
|
1015
1120
|
savedWorkoutSetExerciseId: args.savedWorkoutSetExerciseId,
|
|
1016
1121
|
athleteId: coerceInt(row.user_id),
|
|
1017
1122
|
newExerciseId: coerceInt(row.exercise_id) ?? args.exerciseId,
|
|
1018
|
-
newExerciseTitle: str
|
|
1123
|
+
newExerciseTitle: str(exercise.title),
|
|
1019
1124
|
originalTeamExerciseId: coerceInt(template.exercise_id)
|
|
1020
1125
|
};
|
|
1021
1126
|
}
|
|
@@ -1041,15 +1146,14 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
1041
1146
|
if (!ex) {
|
|
1042
1147
|
const valid = exercises.map((e) => {
|
|
1043
1148
|
const id = coerceInt(e.id);
|
|
1044
|
-
|
|
1045
|
-
return id === null ? null : `${id} (${title})`;
|
|
1149
|
+
return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
|
|
1046
1150
|
}).filter((x) => x !== null);
|
|
1047
1151
|
throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
|
|
1048
1152
|
}
|
|
1049
1153
|
const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
|
|
1050
1154
|
if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
|
|
1051
1155
|
const body = {
|
|
1052
|
-
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
|
|
1156
|
+
...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
|
|
1053
1157
|
...extra
|
|
1054
1158
|
};
|
|
1055
1159
|
const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
|
|
@@ -1059,17 +1163,22 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
|
|
|
1059
1163
|
}
|
|
1060
1164
|
exercisesWritten += 1;
|
|
1061
1165
|
}
|
|
1166
|
+
let setCompleted = false;
|
|
1062
1167
|
if (mode === "log") {
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1168
|
+
if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
|
|
1169
|
+
const setBody = {
|
|
1170
|
+
...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
|
|
1171
|
+
...extra
|
|
1172
|
+
};
|
|
1173
|
+
const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
|
|
1174
|
+
if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
|
|
1175
|
+
setCompleted = true;
|
|
1176
|
+
}
|
|
1069
1177
|
}
|
|
1070
1178
|
return {
|
|
1071
1179
|
savedWorkoutSetId,
|
|
1072
|
-
exercisesWritten
|
|
1180
|
+
exercisesWritten,
|
|
1181
|
+
setCompleted
|
|
1073
1182
|
};
|
|
1074
1183
|
}
|
|
1075
1184
|
/**
|
|
@@ -1112,17 +1221,30 @@ async function addExercisesToWorkout(client, workoutId, exercises) {
|
|
|
1112
1221
|
return res.data;
|
|
1113
1222
|
}
|
|
1114
1223
|
/**
|
|
1224
|
+
* DELETE /v5/programWorkouts/{programWorkoutId} — remove a personal (athlete-created) workout
|
|
1225
|
+
* session from the athlete's own calendar. Re-reads the day and removes ONLY a personal session
|
|
1226
|
+
* (`personal_cal`): it throws if no workout with that id is on the date, or if the target is a
|
|
1227
|
+
* coach-scheduled workout (which is not the athlete's to delete). This guard lives here, at the
|
|
1228
|
+
* delete itself, so no caller can issue the DELETE against a coach workout by skipping a check.
|
|
1229
|
+
* Throws on a non-ok response.
|
|
1230
|
+
*/
|
|
1231
|
+
async function removePersonalWorkout(client, args) {
|
|
1232
|
+
const target = (await fetchAthleteWorkouts(client, args.date, args.date)).find((pw) => coerceInt(pw.id) === args.programWorkoutId);
|
|
1233
|
+
if (target === void 0) throw new Error(`No workout with id ${args.programWorkoutId} on ${args.date}. Get the id and date from athlete_workouts.`);
|
|
1234
|
+
if (!isPersonalSession(target)) throw new Error(`Workout ${args.programWorkoutId} on ${args.date} is a coach-scheduled workout, not a personal session, so it can't be removed. To change logged results on a scheduled workout, use athlete_log_set.`);
|
|
1235
|
+
const res = await client.request("DELETE", `/v5/programWorkouts/${args.programWorkoutId}`);
|
|
1236
|
+
if (!res.ok) throw new Error(`Remove personal workout failed (HTTP ${res.status}).`);
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1115
1239
|
* Find a personal-calendar session already on the given day. The range marks these with
|
|
1116
1240
|
* `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
|
|
1117
1241
|
* first one's workoutId, or null when the day has no personal session.
|
|
1118
1242
|
*/
|
|
1119
1243
|
function findPersonalSessionWorkoutId(workouts) {
|
|
1120
1244
|
for (const pw of workouts) {
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
if (workoutId !== null) return workoutId;
|
|
1125
|
-
}
|
|
1245
|
+
if (!isPersonalSession(pw)) continue;
|
|
1246
|
+
const workoutId = coerceInt(pw.workout_id);
|
|
1247
|
+
if (workoutId !== null) return workoutId;
|
|
1126
1248
|
}
|
|
1127
1249
|
return null;
|
|
1128
1250
|
}
|
|
@@ -1153,7 +1275,11 @@ function indexAddedExercises(added) {
|
|
|
1153
1275
|
}
|
|
1154
1276
|
return out;
|
|
1155
1277
|
}
|
|
1156
|
-
/**
|
|
1278
|
+
/**
|
|
1279
|
+
* Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
|
|
1280
|
+
* carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
|
|
1281
|
+
* title) without re-walking. The one saved-copy traversal the by-exercise paths share.
|
|
1282
|
+
*/
|
|
1157
1283
|
function eachPrescribedExercise(workouts) {
|
|
1158
1284
|
const rows = [];
|
|
1159
1285
|
for (const pw of workouts) {
|
|
@@ -1168,6 +1294,7 @@ function eachPrescribedExercise(workouts) {
|
|
|
1168
1294
|
if (savedWorkoutSetId === null) continue;
|
|
1169
1295
|
const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
|
|
1170
1296
|
for (const ex of exercises) if (isRecord(ex)) rows.push({
|
|
1297
|
+
pw: rec,
|
|
1171
1298
|
savedWorkoutSetId,
|
|
1172
1299
|
ex
|
|
1173
1300
|
});
|
|
@@ -1192,14 +1319,39 @@ function findPrescribedExercise(workouts, exerciseId, used) {
|
|
|
1192
1319
|
}
|
|
1193
1320
|
return null;
|
|
1194
1321
|
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Find prescribed exercises on coach-scheduled (non-personal) workouts that day matching any of the
|
|
1324
|
+
* given exercise ids. Used to warn after an ad-hoc log that the same lift was already on the
|
|
1325
|
+
* athlete's scheduled workout — a caller can then point at {@link logAthleteSet}. Personal sessions
|
|
1326
|
+
* (`personal_cal === true`) are skipped: the ad-hoc log itself lands there, so they are not an
|
|
1327
|
+
* alternative. One row per matching saved-set exercise, dropping any with an unresolvable id.
|
|
1328
|
+
*/
|
|
1329
|
+
function findScheduledMatches(workouts, exerciseIds) {
|
|
1330
|
+
const out = [];
|
|
1331
|
+
for (const { pw, savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
|
|
1332
|
+
if (isPersonalSession(pw)) continue;
|
|
1333
|
+
const exerciseId = coerceInt(ex.exercise_id);
|
|
1334
|
+
const savedWorkoutSetExerciseId = coerceInt(ex.id);
|
|
1335
|
+
if (exerciseId === null || savedWorkoutSetExerciseId === null) continue;
|
|
1336
|
+
if (!exerciseIds.has(exerciseId)) continue;
|
|
1337
|
+
out.push({
|
|
1338
|
+
exerciseId,
|
|
1339
|
+
title: exerciseTitle(ex),
|
|
1340
|
+
program: str(pw.program_title),
|
|
1341
|
+
workoutTitle: str(pw.workout_title) ?? "",
|
|
1342
|
+
savedWorkoutSetId,
|
|
1343
|
+
savedWorkoutSetExerciseId
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
return out;
|
|
1347
|
+
}
|
|
1195
1348
|
/** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
|
|
1196
1349
|
function prescribedExerciseLabels(workouts) {
|
|
1197
1350
|
const labels = [];
|
|
1198
1351
|
for (const { ex } of eachPrescribedExercise(workouts)) {
|
|
1199
1352
|
const id = coerceInt(ex.exercise_id);
|
|
1200
1353
|
if (id === null) continue;
|
|
1201
|
-
|
|
1202
|
-
labels.push(`${id} (${title})`);
|
|
1354
|
+
labels.push(`${id} (${exerciseTitle(ex, "exercise")})`);
|
|
1203
1355
|
}
|
|
1204
1356
|
return labels;
|
|
1205
1357
|
}
|
|
@@ -1226,7 +1378,10 @@ async function logResolvedExercises(client, target, date, resolved) {
|
|
|
1226
1378
|
savedWorkoutSetId,
|
|
1227
1379
|
results
|
|
1228
1380
|
});
|
|
1229
|
-
out.push(
|
|
1381
|
+
out.push({
|
|
1382
|
+
savedWorkoutSetId: written.savedWorkoutSetId,
|
|
1383
|
+
exercisesLogged: written.exercisesLogged
|
|
1384
|
+
});
|
|
1230
1385
|
}
|
|
1231
1386
|
return out;
|
|
1232
1387
|
}
|
|
@@ -1239,7 +1394,8 @@ async function logResolvedExercises(client, target, date, resolved) {
|
|
|
1239
1394
|
*/
|
|
1240
1395
|
async function logAdHocSession(client, args) {
|
|
1241
1396
|
if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
|
|
1242
|
-
const
|
|
1397
|
+
const day = await fetchAthleteWorkouts(client, args.date, args.date);
|
|
1398
|
+
const existing = findPersonalSessionWorkoutId(day);
|
|
1243
1399
|
const created = existing === null;
|
|
1244
1400
|
const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
|
|
1245
1401
|
const withOrder = args.exercises.map((e, i) => ({
|
|
@@ -1263,11 +1419,14 @@ async function logAdHocSession(client, args) {
|
|
|
1263
1419
|
};
|
|
1264
1420
|
});
|
|
1265
1421
|
const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
|
|
1266
|
-
|
|
1422
|
+
const result = {
|
|
1267
1423
|
date: args.date,
|
|
1268
1424
|
created,
|
|
1269
1425
|
sets
|
|
1270
1426
|
};
|
|
1427
|
+
const scheduledAlternatives = findScheduledMatches(day, new Set(args.exercises.map((e) => e.exerciseId)));
|
|
1428
|
+
if (scheduledAlternatives.length > 0) result.scheduledAlternatives = scheduledAlternatives;
|
|
1429
|
+
return result;
|
|
1271
1430
|
}
|
|
1272
1431
|
/**
|
|
1273
1432
|
* Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
|
|
@@ -1304,27 +1463,6 @@ async function logSessionForAthlete(client, args) {
|
|
|
1304
1463
|
sets
|
|
1305
1464
|
};
|
|
1306
1465
|
}
|
|
1307
|
-
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
1308
|
-
function presentExerciseHistory(detail) {
|
|
1309
|
-
return {
|
|
1310
|
-
liftPRs: (detail.liftPRs ?? []).map((p) => ({
|
|
1311
|
-
description: p.description ?? null,
|
|
1312
|
-
reps: p.reps ?? null,
|
|
1313
|
-
weight: p.weight ?? null,
|
|
1314
|
-
units: p.units ?? null,
|
|
1315
|
-
date: p.dateCompleted ?? null
|
|
1316
|
-
})),
|
|
1317
|
-
sessions: (detail.history ?? []).map((h) => ({
|
|
1318
|
-
date: h.dateCompleted,
|
|
1319
|
-
abr: h.abr ?? null,
|
|
1320
|
-
estimated1RM: h.bestEstimated1RM ?? null,
|
|
1321
|
-
sets: (h.sets ?? []).map((s) => ({
|
|
1322
|
-
setNumber: s.setNumber,
|
|
1323
|
-
value: s.formattedValue ?? null
|
|
1324
|
-
}))
|
|
1325
|
-
}))
|
|
1326
|
-
};
|
|
1327
|
-
}
|
|
1328
1466
|
//#endregion
|
|
1329
1467
|
//#region src/coach.ts
|
|
1330
1468
|
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
@@ -2148,7 +2286,7 @@ async function removeSession(client, programId, pwId) {
|
|
|
2148
2286
|
async function publishSession(client, pwId) {
|
|
2149
2287
|
await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
|
|
2150
2288
|
}
|
|
2151
|
-
function str(value) {
|
|
2289
|
+
function str$1(value) {
|
|
2152
2290
|
return value === void 0 || value === null ? "" : String(value);
|
|
2153
2291
|
}
|
|
2154
2292
|
async function readSession(client, programId, date, pwId) {
|
|
@@ -2161,9 +2299,9 @@ async function readSession(client, programId, date, pwId) {
|
|
|
2161
2299
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2162
2300
|
return {
|
|
2163
2301
|
pwId,
|
|
2164
|
-
date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
|
|
2302
|
+
date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
|
|
2165
2303
|
published: pw.published,
|
|
2166
|
-
instruction: str(pw.instruction),
|
|
2304
|
+
instruction: str$1(pw.instruction),
|
|
2167
2305
|
blocks
|
|
2168
2306
|
};
|
|
2169
2307
|
}
|
|
@@ -2174,7 +2312,7 @@ function readBlock(b) {
|
|
|
2174
2312
|
const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
|
|
2175
2313
|
return {
|
|
2176
2314
|
order: Number(b.order),
|
|
2177
|
-
title: str(b.title),
|
|
2315
|
+
title: str$1(b.title),
|
|
2178
2316
|
leaderboard,
|
|
2179
2317
|
exercises
|
|
2180
2318
|
};
|
|
@@ -2183,19 +2321,19 @@ function readExercise(ex) {
|
|
|
2183
2321
|
const reps = [];
|
|
2184
2322
|
const load = [];
|
|
2185
2323
|
for (let i = 1; i <= 10; i += 1) {
|
|
2186
|
-
const r = str(ex[`param_1_data_${i}`]);
|
|
2324
|
+
const r = str$1(ex[`param_1_data_${i}`]);
|
|
2187
2325
|
if (r !== "") reps.push(r);
|
|
2188
|
-
const w = str(ex[`param_2_data_${i}`]);
|
|
2326
|
+
const w = str$1(ex[`param_2_data_${i}`]);
|
|
2189
2327
|
if (w !== "") load.push(w);
|
|
2190
2328
|
}
|
|
2191
2329
|
return {
|
|
2192
2330
|
order: Number(ex.order),
|
|
2193
|
-
title: str(ex.title),
|
|
2331
|
+
title: str$1(ex.title),
|
|
2194
2332
|
reps,
|
|
2195
2333
|
primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
|
|
2196
2334
|
load,
|
|
2197
2335
|
loadUnit: unitLabel(coerceInt(ex.param_2_type)),
|
|
2198
|
-
instruction: str(ex.instruction)
|
|
2336
|
+
instruction: str$1(ex.instruction)
|
|
2199
2337
|
};
|
|
2200
2338
|
}
|
|
2201
2339
|
//#endregion
|
|
@@ -2431,4 +2569,4 @@ var ExerciseLibrary = class {
|
|
|
2431
2569
|
}
|
|
2432
2570
|
};
|
|
2433
2571
|
//#endregion
|
|
2434
|
-
export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, 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, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
|
|
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 };
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/alandotcom/trainheroic-unofficial.git",
|
|
8
8
|
"directory": "packages/js"
|
|
9
9
|
},
|
|
10
|
-
"description": "Unofficial TypeScript SDK for the TrainHeroic
|
|
10
|
+
"description": "Unofficial TypeScript SDK for the TrainHeroic API.",
|
|
11
11
|
"type": "module",
|
|
12
12
|
"exports": {
|
|
13
13
|
".": {
|
|
@@ -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.6.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.0.0",
|