@trainheroic-unofficial/js 4.1.1 → 4.3.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 +23 -15
- package/dist/index.d.mts +74 -59
- package/dist/index.mjs +281 -112
- package/dist/{library-cache-CDABOdIN.d.mts → library-cache-TkOsfh5m.d.mts} +0 -2
- package/dist/node.d.mts +2 -4
- package/dist/node.mjs +1 -2
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -221,9 +221,6 @@ import { buildSession, type BlockSpec } from "@trainheroic-unofficial/js";
|
|
|
221
221
|
|
|
222
222
|
const { match } = await library.resolve("Back Squat");
|
|
223
223
|
if (!match) throw new Error("Resolve to a single exercise before building.");
|
|
224
|
-
if (match.units[0] !== "reps" || match.units[1] !== "lb") {
|
|
225
|
-
throw new Error("Choose an exercise with reps and pounds as its fixed units.");
|
|
226
|
-
}
|
|
227
224
|
|
|
228
225
|
const blocks: BlockSpec[] = [
|
|
229
226
|
{
|
|
@@ -257,14 +254,16 @@ Each exercise needs an `id`; `sets`, `reps`, `weight`, `rpe`, and a per-exercise
|
|
|
257
254
|
optional. `reps` and `weight` take a scalar (broadcast across every set) or a per-set array
|
|
258
255
|
like `reps: [5, 5, 3]`. State `primaryUnit` for `reps` and `secondaryUnit` for `weight`.
|
|
259
256
|
The full field list is `ExerciseSpec` / `BlockSpec` in
|
|
260
|
-
[`@trainheroic-unofficial/dto`](../dto). `buildSession`
|
|
261
|
-
|
|
257
|
+
[`@trainheroic-unofficial/dto`](../dto). `buildSession` keeps an exercise's default unit when
|
|
258
|
+
the stated unit matches it and sets any other stated unit on this session, as described under "The workout encoder".
|
|
262
259
|
|
|
263
260
|
`buildSession` returns `{ pwId, workoutId, advisories }`: `pwId` is the program-workout id (the
|
|
264
261
|
placement of the session in the program, which is the handle subsequent calls take), and
|
|
265
262
|
`workoutId` is the underlying workout id. Use `pwId` with `readSession(client, programId, date, pwId)`
|
|
266
|
-
to read the session back
|
|
267
|
-
`removeSession(client, programId, pwId)` deletes it.
|
|
263
|
+
to read the session back; the read-back also carries `workoutId`. `publishSession(client, pwId)`
|
|
264
|
+
publishes it later; `removeSession(client, programId, pwId)` deletes it.
|
|
265
|
+
`saveSessionAsTemplate(client, { workoutId, pwId, title })` copies the session into the coach's
|
|
266
|
+
session library.
|
|
268
267
|
|
|
269
268
|
## Reading athlete training
|
|
270
269
|
|
|
@@ -314,14 +313,23 @@ console.log(analyticsMetricCatalog());
|
|
|
314
313
|
`buildSession` calls the encoder for you; you only deal with it directly to preview values.
|
|
315
314
|
TrainHeroic's exercise payload expects every parameter slot present, so the encoder fills all
|
|
316
315
|
of them (empty slots included) to avoid an HTTP 500. A scalar prescription is broadcast across
|
|
317
|
-
the set count.
|
|
318
|
-
load
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
316
|
+
the set count. The `rpe` field goes into the instruction text; to prescribe RPE as a structured
|
|
317
|
+
load, put the values in `weight` with `secondaryUnit: "RPE"`. Each populated slot in a spec
|
|
318
|
+
states its unit, and `resolveExerciseUnits` maps that unit to a TrainHeroic param type. It keeps
|
|
319
|
+
the exercise's library default when the default already has the stated unit, and otherwise uses
|
|
320
|
+
the stated unit's own type, so a spec can prescribe `%max` on a pounds lift or meters on a miles
|
|
321
|
+
exercise. It throws before any write when a unit is unknown, conflicts with an explicit
|
|
322
|
+
`param_N_type`, or names two types (`sec` and `in`; set `param_N_type` to choose).
|
|
323
|
+
|
|
324
|
+
TrainHeroic stores a newly inserted exercise row with the library's param types whatever the
|
|
325
|
+
request says, and keeps the requested types when the same row is saved again by id (the coach
|
|
326
|
+
web app's unit picker works this way). `buildSession` therefore re-saves by id each row whose
|
|
327
|
+
stored types differ from the resolved ones, and throws if TrainHeroic still does not keep them.
|
|
328
|
+
|
|
329
|
+
`buildSession` returns the resolver's non-blocking notes and warnings in `advisories`; a note
|
|
330
|
+
names each unit set in place of an exercise's default. Call `collectAdvisories` to preview
|
|
331
|
+
validation without writing a workout. Resolution fetches current defaults from TrainHeroic; an
|
|
332
|
+
unavailable library response stops the build.
|
|
325
333
|
|
|
326
334
|
## Develop
|
|
327
335
|
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-
|
|
2
|
-
import { Advisory, AthleteExerciseNoteOutput, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutNoteOutput, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
|
|
1
|
+
import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-TkOsfh5m.mjs";
|
|
2
|
+
import { Advisory, AthleteExerciseNoteOutput, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutNoteOutput, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionSaveAsTemplate, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
|
|
3
3
|
import { chunk } from "es-toolkit/array";
|
|
4
4
|
import { ZodType } from "zod";
|
|
5
5
|
export * from "@trainheroic-unofficial/dto";
|
|
6
|
-
//#region src/http-error.d.ts
|
|
7
6
|
type JsonScalar = boolean | number | string | null;
|
|
8
7
|
type RequestBodySummary = {
|
|
9
8
|
type: "array";
|
|
@@ -33,13 +32,26 @@ export declare class TrainHeroicHttpError extends Error {
|
|
|
33
32
|
readonly responseBody: unknown;
|
|
34
33
|
constructor(method: string, url: string, status: number, diagnostics?: TrainHeroicHttpErrorDiagnostics);
|
|
35
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* True for statuses that mean TrainHeroic's servers could not be reached or did not answer: a
|
|
37
|
+
* gateway failure (502, 503, 504) or a Cloudflare edge error (520-530). TrainHeroic sits behind
|
|
38
|
+
* Cloudflare, so a 522 means the edge timed out connecting to TrainHeroic's origin. These describe
|
|
39
|
+
* an upstream outage, so the same request can succeed when retried later.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isTrainHeroicUnavailableStatus(status: number): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Thrown when TrainHeroic answers with an outage status (see `isTrainHeroicUnavailableStatus`).
|
|
44
|
+
* The message tells the reader to retry later, so a model relaying it does not ask the user to
|
|
45
|
+
* re-check credentials that are fine.
|
|
46
|
+
*/
|
|
47
|
+
export declare class TrainHeroicUnavailableError extends Error {
|
|
48
|
+
readonly name = "TrainHeroicUnavailableError";
|
|
49
|
+
readonly status: number;
|
|
50
|
+
constructor(status: number);
|
|
51
|
+
}
|
|
36
52
|
type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/transport.d.ts
|
|
39
53
|
/** The HTTP seam used by the SDK. It defaults to global `fetch` and stays injectable for hosts. */
|
|
40
54
|
type TrainHeroicTransport = (url: string, init: RequestInit) => Promise<Response>;
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region src/auth.d.ts
|
|
43
55
|
export type TrainHeroicSession = {
|
|
44
56
|
thUserId: number;
|
|
45
57
|
sessionId: string;
|
|
@@ -53,14 +65,14 @@ export type LoginOptions = {
|
|
|
53
65
|
transport?: TrainHeroicTransport;
|
|
54
66
|
};
|
|
55
67
|
/**
|
|
56
|
-
* Authenticate against TrainHeroic. Returns the session bundle, or null
|
|
57
|
-
*
|
|
68
|
+
* Authenticate against TrainHeroic. Returns the session bundle, or null when TrainHeroic
|
|
69
|
+
* rejects the login. Throws `TrainHeroicUnavailableError` when TrainHeroic is unreachable (an
|
|
70
|
+
* outage status such as a Cloudflare 522), so callers can tell the user to retry later.
|
|
71
|
+
* TrainHeroic returns only { id, scope, role, session_id } (verified in
|
|
58
72
|
* the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
|
|
59
73
|
* is sent as the `session-token` header and works against both API hosts.
|
|
60
74
|
*/
|
|
61
75
|
export declare function loginTrainHeroic(email: string, password: string, options?: LoginOptions): Promise<TrainHeroicSession | null>;
|
|
62
|
-
//#endregion
|
|
63
|
-
//#region src/client.d.ts
|
|
64
76
|
export declare class TrainHeroicAuthError extends Error {
|
|
65
77
|
name: string;
|
|
66
78
|
}
|
|
@@ -111,21 +123,17 @@ export declare class TrainHeroicClient {
|
|
|
111
123
|
get sessionId(): string | null;
|
|
112
124
|
request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<ClientResult<T>>;
|
|
113
125
|
}
|
|
114
|
-
//#endregion
|
|
115
|
-
//#region src/response-check.d.ts
|
|
116
126
|
/**
|
|
117
127
|
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
118
128
|
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
119
129
|
* when TrainHeroic renames or drops a field we read.
|
|
120
130
|
*/
|
|
121
131
|
export declare function checkResponse(schema: ZodType, data: unknown, label: string): void;
|
|
122
|
-
//#endregion
|
|
123
|
-
//#region src/exercise-util.d.ts
|
|
124
132
|
/**
|
|
125
|
-
* Display labels for TrainHeroic parameter types.
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
133
|
+
* Display labels for TrainHeroic parameter types. Each library exercise has a default type per
|
|
134
|
+
* slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
|
|
135
|
+
* A session can set a different type on an exercise; the workout builder maps a stated unit
|
|
136
|
+
* back to its type code through this table, so keep it in sync with the builder's unit aliases.
|
|
129
137
|
*/
|
|
130
138
|
export declare const PARAM_UNIT: Readonly<Record<number, string | null>>;
|
|
131
139
|
export declare const PARAM_NONE = 0;
|
|
@@ -140,7 +148,7 @@ export declare function coerceInt(value: unknown): number | null;
|
|
|
140
148
|
export declare function coerceNum(value: unknown): number | null;
|
|
141
149
|
export declare function unitLabel(paramType: unknown): string | null;
|
|
142
150
|
/**
|
|
143
|
-
*
|
|
151
|
+
* Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
|
|
144
152
|
* Positional, not semantic: some exercises reverse the slots, so the array is not labelled
|
|
145
153
|
* by role. A null entry is an unset slot.
|
|
146
154
|
*/
|
|
@@ -232,8 +240,6 @@ export interface ExerciseIndex {
|
|
|
232
240
|
recordDelete(id: number): Promise<void>;
|
|
233
241
|
stats(): Promise<Record<string, unknown>>;
|
|
234
242
|
}
|
|
235
|
-
//#endregion
|
|
236
|
-
//#region src/athlete.d.ts
|
|
237
243
|
/**
|
|
238
244
|
* The logged-in account's numeric user id (the athlete warehouse's tenant key, and a required
|
|
239
245
|
* query arg for several athlete endpoints). Works from any session — coach or athlete — and
|
|
@@ -406,8 +412,6 @@ export declare function summarizeAthleteWorkouts(list: readonly AthleteWorkoutVi
|
|
|
406
412
|
export declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId: number, year: number, month: number): CoachAthleteTraining;
|
|
407
413
|
/** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
|
|
408
414
|
export declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
|
|
409
|
-
//#endregion
|
|
410
|
-
//#region src/exercise-history.d.ts
|
|
411
415
|
/**
|
|
412
416
|
* Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
|
|
413
417
|
* The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
|
|
@@ -416,8 +420,6 @@ export declare function presentExerciseHistory(detail: ExerciseHistoryDetail): P
|
|
|
416
420
|
* tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
|
|
417
421
|
*/
|
|
418
422
|
export declare function historyInRange(presented: PresentedExerciseHistory, since: string | undefined, until: string | undefined): PresentedExerciseHistory;
|
|
419
|
-
//#endregion
|
|
420
|
-
//#region src/coach-athlete-calendar.d.ts
|
|
421
423
|
/**
|
|
422
424
|
* A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
|
|
423
425
|
* YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
|
|
@@ -425,11 +427,20 @@ export declare function historyInRange(presented: PresentedExerciseHistory, sinc
|
|
|
425
427
|
* `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
|
|
426
428
|
*/
|
|
427
429
|
export declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
|
|
430
|
+
/** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
|
|
431
|
+
export declare class CoachMonthSummaryError extends Error {
|
|
432
|
+
readonly name = "CoachMonthSummaryError";
|
|
433
|
+
readonly status: number;
|
|
434
|
+
constructor(message: string, status: number);
|
|
435
|
+
}
|
|
428
436
|
/**
|
|
429
437
|
* A coach's month view of a roster athlete's logged sessions
|
|
430
438
|
* (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
|
|
431
439
|
* ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
|
|
432
440
|
* `userId` in each row is the roster athlete, not the calling coach.
|
|
441
|
+
*
|
|
442
|
+
* TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
|
|
443
|
+
* read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
|
|
433
444
|
*/
|
|
434
445
|
export declare function fetchCoachAthleteCalendarSummary(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<unknown[]>;
|
|
435
446
|
/** A roster athlete's coach-writable calendar (from `GET /v5/calendars/athletes/{id}`). */
|
|
@@ -460,8 +471,6 @@ export declare function resolveBuildProgramId(client: TrainHeroicClient, args: {
|
|
|
460
471
|
athleteId?: number;
|
|
461
472
|
date?: string;
|
|
462
473
|
}): Promise<number>;
|
|
463
|
-
//#endregion
|
|
464
|
-
//#region src/exercise-set-payload.d.ts
|
|
465
474
|
type SetWriteMode = "log" | "prescribe";
|
|
466
475
|
type ExerciseSetInput = {
|
|
467
476
|
param1?: number | string;
|
|
@@ -484,8 +493,6 @@ type ExerciseSetPayload = Record<string, unknown> & {
|
|
|
484
493
|
* full payload and never marks slots or the exercise complete.
|
|
485
494
|
*/
|
|
486
495
|
export declare function buildExerciseSetPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly ExerciseSetInput[], mode: SetWriteMode, existing?: Record<string, unknown>): ExerciseSetPayload;
|
|
487
|
-
//#endregion
|
|
488
|
-
//#region src/athlete-set-write.d.ts
|
|
489
496
|
/**
|
|
490
497
|
* One set of entered values for a single exercise within a saved workout set.
|
|
491
498
|
* `param1` and `param2` correspond to the exercise's first and second parameter types
|
|
@@ -758,8 +765,6 @@ export declare function logSessionForAthlete(client: TrainHeroicClient, args: {
|
|
|
758
765
|
date: string;
|
|
759
766
|
exercises: readonly SessionExercise[];
|
|
760
767
|
}): Promise<LogSessionResult>;
|
|
761
|
-
//#endregion
|
|
762
|
-
//#region src/athlete-workout-note.d.ts
|
|
763
768
|
/**
|
|
764
769
|
* PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
|
|
765
770
|
* workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
|
|
@@ -772,8 +777,6 @@ export declare function setAthleteWorkoutNote(client: TrainHeroicClient, args: {
|
|
|
772
777
|
notes?: string | undefined;
|
|
773
778
|
rpe?: number | undefined;
|
|
774
779
|
}): Promise<AthleteWorkoutNoteOutput>;
|
|
775
|
-
//#endregion
|
|
776
|
-
//#region src/athlete-exercise-note.d.ts
|
|
777
780
|
/**
|
|
778
781
|
* PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
|
|
779
782
|
* "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
|
|
@@ -784,8 +787,6 @@ export declare function setAthleteExerciseNote(client: TrainHeroicClient, args:
|
|
|
784
787
|
savedWorkoutSetExerciseId: number | string;
|
|
785
788
|
notes: string;
|
|
786
789
|
}): Promise<AthleteExerciseNoteOutput>;
|
|
787
|
-
//#endregion
|
|
788
|
-
//#region src/workout-export.d.ts
|
|
789
790
|
export type WorkoutExportFormat = "json" | "csv" | "text";
|
|
790
791
|
/** A serialized export ready to write to a file or hand to a browser download. */
|
|
791
792
|
export type SerializedExport = {
|
|
@@ -808,8 +809,6 @@ export declare function workoutsToText(workouts: readonly WorkoutHistoryExport[]
|
|
|
808
809
|
export declare function serializeWorkoutHistory(workouts: readonly WorkoutHistoryExport[], format: WorkoutExportFormat, opts?: {
|
|
809
810
|
filenameBase?: string;
|
|
810
811
|
}): SerializedExport;
|
|
811
|
-
//#endregion
|
|
812
|
-
//#region src/main-lifts.d.ts
|
|
813
812
|
export type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
|
|
814
813
|
export type MainLiftFamily = {
|
|
815
814
|
key: MainLiftFamilyKey;
|
|
@@ -891,8 +890,6 @@ export declare function fetchRosterMainLiftPRs(client: TrainHeroicClient, opts?:
|
|
|
891
890
|
now?: Date;
|
|
892
891
|
concurrency?: number;
|
|
893
892
|
}): Promise<AthleteMainLiftPRs[]>;
|
|
894
|
-
//#endregion
|
|
895
|
-
//#region src/coach.d.ts
|
|
896
893
|
export declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
897
894
|
export declare const PROGRAM_KINDS: readonly ["calendar", "fixed"];
|
|
898
895
|
export type ProgramKind = (typeof PROGRAM_KINDS)[number];
|
|
@@ -1055,10 +1052,17 @@ export declare function teamVolume(client: TrainHeroicClient, args: {
|
|
|
1055
1052
|
}): Promise<TeamVolumeReport>;
|
|
1056
1053
|
/** Create a reusable session template in the coach library (`POST /v5/sessions/template`). */
|
|
1057
1054
|
export declare function createSessionTemplate(client: TrainHeroicClient, args: SessionTemplateCreate): Promise<Record<string, unknown>>;
|
|
1055
|
+
/**
|
|
1056
|
+
* Copy an existing calendar session, with its blocks and exercises, into the coach's session
|
|
1057
|
+
* library as a new template
|
|
1058
|
+
* (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
|
|
1059
|
+
* the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
|
|
1060
|
+
* the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
|
|
1061
|
+
* has no `id`, or when the two ids are swapped.
|
|
1062
|
+
*/
|
|
1063
|
+
export declare function saveSessionAsTemplate(client: TrainHeroicClient, args: SessionSaveAsTemplate): Promise<Record<string, unknown>>;
|
|
1058
1064
|
/** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
|
|
1059
1065
|
export declare const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
|
|
1060
|
-
//#endregion
|
|
1061
|
-
//#region src/util.d.ts
|
|
1062
1066
|
/**
|
|
1063
1067
|
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
1064
1068
|
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
@@ -1069,8 +1073,6 @@ export declare const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&p
|
|
|
1069
1073
|
* definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
|
|
1070
1074
|
*/
|
|
1071
1075
|
export declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclude<T[K], undefined>; };
|
|
1072
|
-
//#endregion
|
|
1073
|
-
//#region src/workout-encode.d.ts
|
|
1074
1076
|
type AdvisoryIndex = Pick<ExerciseIndex, "currentDefaultsMany">;
|
|
1075
1077
|
export type SetSplit = {
|
|
1076
1078
|
blockTitle: string;
|
|
@@ -1109,19 +1111,37 @@ export declare const BLOCK_TYPE_HYPERTROPHY = 2;
|
|
|
1109
1111
|
*/
|
|
1110
1112
|
export declare function defaultBlockType(block: BlockSpec): number;
|
|
1111
1113
|
export declare function buildBlockPayload(blocks: readonly BlockSpec[], workoutId: number): Array<Record<string, unknown>>;
|
|
1112
|
-
/** Flag spec params the API will silently override to the exercise's fixed units. */
|
|
1113
|
-
export declare function unitAdvisory(blockTitle: string, ex: ExerciseSpec, defaults: {
|
|
1114
|
-
param1: number | null;
|
|
1115
|
-
param2: number | null;
|
|
1116
|
-
}): Advisory;
|
|
1117
1114
|
/**
|
|
1118
|
-
*
|
|
1119
|
-
*
|
|
1120
|
-
*
|
|
1115
|
+
* The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
|
|
1116
|
+
* other than the library default. This is the one definition of a unit override: the advisory
|
|
1117
|
+
* notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
|
|
1118
|
+
* exactly these types.
|
|
1119
|
+
*/
|
|
1120
|
+
export declare function overriddenSlots(ex: ExerciseSpec, defaults: ExerciseDefaults): Array<1 | 2>;
|
|
1121
|
+
/**
|
|
1122
|
+
* Describe how a resolved exercise's units relate to its library defaults, and flag spec
|
|
1123
|
+
* fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
|
|
1124
|
+
* (from `resolveExerciseUnits`).
|
|
1125
|
+
*/
|
|
1126
|
+
export declare function unitAdvisory(label: string, ex: ExerciseSpec, defaults: ExerciseDefaults): Advisory;
|
|
1127
|
+
/** A block list with resolved param types, the library defaults used, and advisories. */
|
|
1128
|
+
export type ResolvedUnits = {
|
|
1129
|
+
blocks: BlockSpec[];
|
|
1130
|
+
defaultsById: Map<number, ExerciseDefaults>;
|
|
1131
|
+
advisories: Advisory;
|
|
1132
|
+
};
|
|
1133
|
+
/**
|
|
1134
|
+
* Resolve every exercise's param types against current TrainHeroic exercise data and collect
|
|
1135
|
+
* non-blocking advisories. Throws, before anything is written, when a populated slot has no
|
|
1136
|
+
* stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
|
|
1137
|
+
* returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
|
|
1138
|
+
*/
|
|
1139
|
+
export declare function resolveExerciseUnits(blocks: readonly BlockSpec[], index: AdvisoryIndex): Promise<ResolvedUnits>;
|
|
1140
|
+
/**
|
|
1141
|
+
* Validate units and collect advisories without writing a workout. This is the preview entry
|
|
1142
|
+
* point; `resolveExerciseUnits` also returns the resolved blocks that `buildSession` writes.
|
|
1121
1143
|
*/
|
|
1122
1144
|
export declare function collectAdvisories(blocks: readonly BlockSpec[], index: AdvisoryIndex): Promise<Advisory>;
|
|
1123
|
-
//#endregion
|
|
1124
|
-
//#region src/workout-session.d.ts
|
|
1125
1145
|
export type BuildOptions = {
|
|
1126
1146
|
programId: number;
|
|
1127
1147
|
blocks: BlockSpec[];
|
|
@@ -1156,8 +1176,6 @@ export declare function setSessionInstruction(client: TrainHeroicClient, workout
|
|
|
1156
1176
|
export declare function removeSession(client: TrainHeroicClient, programId: number, pwId: number): Promise<void>;
|
|
1157
1177
|
export declare function publishSession(client: TrainHeroicClient, pwId: number): Promise<void>;
|
|
1158
1178
|
export declare function readSession(client: TrainHeroicClient, programId: number, date: WorkoutDate, pwId: number): Promise<ReadResult>;
|
|
1159
|
-
//#endregion
|
|
1160
|
-
//#region src/messaging.d.ts
|
|
1161
1179
|
/** Live list of chat streams, flattened to (stream, kind) tuples. */
|
|
1162
1180
|
export declare function fetchStreams(client: TrainHeroicClient): Promise<Array<{
|
|
1163
1181
|
stream: Record<string, unknown>;
|
|
@@ -1171,8 +1189,6 @@ export declare function buildCommentPayload(streamId: number, text: string, repl
|
|
|
1171
1189
|
export declare function sendComment(client: TrainHeroicClient, streamId: number, text: string, replyTo?: number | null): Promise<Record<string, unknown>>;
|
|
1172
1190
|
export declare function deleteComment(client: TrainHeroicClient, streamId: number, commentId: number): Promise<unknown>;
|
|
1173
1191
|
export declare function readLive(client: TrainHeroicClient, streamId: number, limit?: number, afterCommentId?: number): Promise<unknown[]>;
|
|
1174
|
-
//#endregion
|
|
1175
|
-
//#region src/exercise-index.d.ts
|
|
1176
1192
|
/** Read current parameter types without refreshing or trusting the search mirror. */
|
|
1177
1193
|
export declare function fetchCurrentExerciseDefaults(client: TrainHeroicClient, ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
|
|
1178
1194
|
/**
|
|
@@ -1196,5 +1212,4 @@ export declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
1196
1212
|
recordDelete(id: number): Promise<void>;
|
|
1197
1213
|
stats(): Promise<Record<string, unknown>>;
|
|
1198
1214
|
}
|
|
1199
|
-
//#endregion
|
|
1200
1215
|
export { type ExerciseSetInput, type ExerciseSetPayload, LibraryCache, LibrarySnapshot, MemoryLibraryCache, type RequestBodySummary, type SetWriteMode, type TrainHeroicHttpErrorDiagnostics, type TrainHeroicHttpErrorHandler, type TrainHeroicTransport, chunk };
|
package/dist/index.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema,
|
|
|
2
2
|
import { chunk, uniq } from "es-toolkit/array";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
export * from "@trainheroic-unofficial/dto";
|
|
5
|
-
|
|
5
|
+
// src/date-window.ts
|
|
6
6
|
const DAY_MS = 864e5;
|
|
7
7
|
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
8
8
|
const MAX_DATE_WINDOWS = 100;
|
|
@@ -35,8 +35,7 @@ function splitDateRange(start, end, maxDays) {
|
|
|
35
35
|
});
|
|
36
36
|
return windows;
|
|
37
37
|
}
|
|
38
|
-
|
|
39
|
-
//#region src/http-error.ts
|
|
38
|
+
// src/http-error.ts
|
|
40
39
|
const MAX_REQUEST_KEYS = 50;
|
|
41
40
|
const MAX_RESPONSE_DEPTH = 4;
|
|
42
41
|
const MAX_RESPONSE_KEYS = 20;
|
|
@@ -243,6 +242,28 @@ var TrainHeroicHttpError = class extends Error {
|
|
|
243
242
|
this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
|
|
244
243
|
}
|
|
245
244
|
};
|
|
245
|
+
/**
|
|
246
|
+
* True for statuses that mean TrainHeroic's servers could not be reached or did not answer: a
|
|
247
|
+
* gateway failure (502, 503, 504) or a Cloudflare edge error (520-530). TrainHeroic sits behind
|
|
248
|
+
* Cloudflare, so a 522 means the edge timed out connecting to TrainHeroic's origin. These describe
|
|
249
|
+
* an upstream outage, so the same request can succeed when retried later.
|
|
250
|
+
*/
|
|
251
|
+
function isTrainHeroicUnavailableStatus(status) {
|
|
252
|
+
return status === 502 || status === 503 || status === 504 || status >= 520 && status <= 530;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Thrown when TrainHeroic answers with an outage status (see `isTrainHeroicUnavailableStatus`).
|
|
256
|
+
* The message tells the reader to retry later, so a model relaying it does not ask the user to
|
|
257
|
+
* re-check credentials that are fine.
|
|
258
|
+
*/
|
|
259
|
+
var TrainHeroicUnavailableError = class extends Error {
|
|
260
|
+
name = "TrainHeroicUnavailableError";
|
|
261
|
+
status;
|
|
262
|
+
constructor(status) {
|
|
263
|
+
super(`TrainHeroic is not responding right now (HTTP ${status}). Try again in a few minutes.`);
|
|
264
|
+
this.status = status;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
246
267
|
/** Call observability hooks without allowing them to change SDK behavior. */
|
|
247
268
|
function notifyHttpError(handler, method, url, status, diagnostics = {}) {
|
|
248
269
|
if (!handler) return;
|
|
@@ -250,11 +271,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
|
|
|
250
271
|
Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
|
|
251
272
|
} catch {}
|
|
252
273
|
}
|
|
253
|
-
|
|
254
|
-
//#region src/transport.ts
|
|
274
|
+
// src/transport.ts
|
|
255
275
|
const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
|
|
256
|
-
|
|
257
|
-
//#region src/auth.ts
|
|
276
|
+
// src/auth.ts
|
|
258
277
|
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
259
278
|
/**
|
|
260
279
|
* The login endpoint, allowing an env override so a test harness can authenticate against a local
|
|
@@ -270,8 +289,10 @@ function authUrl() {
|
|
|
270
289
|
return DEFAULT_AUTH_URL;
|
|
271
290
|
}
|
|
272
291
|
/**
|
|
273
|
-
* Authenticate against TrainHeroic. Returns the session bundle, or null
|
|
274
|
-
*
|
|
292
|
+
* Authenticate against TrainHeroic. Returns the session bundle, or null when TrainHeroic
|
|
293
|
+
* rejects the login. Throws `TrainHeroicUnavailableError` when TrainHeroic is unreachable (an
|
|
294
|
+
* outage status such as a Cloudflare 522), so callers can tell the user to retry later.
|
|
295
|
+
* TrainHeroic returns only { id, scope, role, session_id } (verified in
|
|
275
296
|
* the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
|
|
276
297
|
* is sent as the `session-token` header and works against both API hosts.
|
|
277
298
|
*/
|
|
@@ -291,6 +312,7 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
291
312
|
if (!res.ok) {
|
|
292
313
|
await res.body?.cancel().catch(() => {});
|
|
293
314
|
notifyHttpError(options.onHttpError, "POST", url, res.status);
|
|
315
|
+
if (isTrainHeroicUnavailableStatus(res.status)) throw new TrainHeroicUnavailableError(res.status);
|
|
294
316
|
return null;
|
|
295
317
|
}
|
|
296
318
|
const data = await res.json().catch(() => null);
|
|
@@ -302,13 +324,12 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
302
324
|
role: data.role ?? ""
|
|
303
325
|
};
|
|
304
326
|
}
|
|
305
|
-
|
|
306
|
-
//#region src/exercise-util.ts
|
|
327
|
+
// src/exercise-util.ts
|
|
307
328
|
/**
|
|
308
|
-
* Display labels for TrainHeroic parameter types.
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
329
|
+
* Display labels for TrainHeroic parameter types. Each library exercise has a default type per
|
|
330
|
+
* slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
|
|
331
|
+
* A session can set a different type on an exercise; the workout builder maps a stated unit
|
|
332
|
+
* back to its type code through this table, so keep it in sync with the builder's unit aliases.
|
|
312
333
|
*/
|
|
313
334
|
const PARAM_UNIT = {
|
|
314
335
|
0: null,
|
|
@@ -357,7 +378,7 @@ function unitLabel(paramType) {
|
|
|
357
378
|
return PARAM_UNIT[t] ?? null;
|
|
358
379
|
}
|
|
359
380
|
/**
|
|
360
|
-
*
|
|
381
|
+
* Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
|
|
361
382
|
* Positional, not semantic: some exercises reverse the slots, so the array is not labelled
|
|
362
383
|
* by role. A null entry is an unset slot.
|
|
363
384
|
*/
|
|
@@ -554,8 +575,7 @@ function createLimiter(max) {
|
|
|
554
575
|
function assertPositiveInteger(value, label) {
|
|
555
576
|
if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
|
|
556
577
|
}
|
|
557
|
-
|
|
558
|
-
//#region src/client.ts
|
|
578
|
+
// src/client.ts
|
|
559
579
|
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
560
580
|
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
561
581
|
const MAX_REQUEST_CONCURRENCY = 4;
|
|
@@ -675,8 +695,7 @@ var TrainHeroicClient = class {
|
|
|
675
695
|
return this.#transport(url, init);
|
|
676
696
|
}
|
|
677
697
|
};
|
|
678
|
-
|
|
679
|
-
//#region src/response-check.ts
|
|
698
|
+
// src/response-check.ts
|
|
680
699
|
/**
|
|
681
700
|
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
682
701
|
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
@@ -689,8 +708,7 @@ function checkResponse(schema, data, label) {
|
|
|
689
708
|
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
690
709
|
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
691
710
|
}
|
|
692
|
-
|
|
693
|
-
//#region src/athlete.ts
|
|
711
|
+
// src/athlete.ts
|
|
694
712
|
async function getJson(client, path, label) {
|
|
695
713
|
const res = await client.request("GET", path);
|
|
696
714
|
if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
@@ -1426,8 +1444,7 @@ function presentExerciseHistory(detail) {
|
|
|
1426
1444
|
}))
|
|
1427
1445
|
};
|
|
1428
1446
|
}
|
|
1429
|
-
|
|
1430
|
-
//#region src/exercise-history.ts
|
|
1447
|
+
// src/exercise-history.ts
|
|
1431
1448
|
/**
|
|
1432
1449
|
* Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
|
|
1433
1450
|
* The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
|
|
@@ -1448,8 +1465,7 @@ function historyInRange(presented, since, until) {
|
|
|
1448
1465
|
sessions
|
|
1449
1466
|
};
|
|
1450
1467
|
}
|
|
1451
|
-
|
|
1452
|
-
//#region src/coach-athlete-calendar.ts
|
|
1468
|
+
// src/coach-athlete-calendar.ts
|
|
1453
1469
|
async function getArray(client, path, label) {
|
|
1454
1470
|
const res = await client.request("GET", path);
|
|
1455
1471
|
if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
|
|
@@ -1464,14 +1480,34 @@ async function getArray(client, path, label) {
|
|
|
1464
1480
|
function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
|
|
1465
1481
|
return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
|
|
1466
1482
|
}
|
|
1483
|
+
/** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
|
|
1484
|
+
var CoachMonthSummaryError = class extends Error {
|
|
1485
|
+
name = "CoachMonthSummaryError";
|
|
1486
|
+
status;
|
|
1487
|
+
constructor(message, status) {
|
|
1488
|
+
super(message);
|
|
1489
|
+
this.status = status;
|
|
1490
|
+
}
|
|
1491
|
+
};
|
|
1467
1492
|
/**
|
|
1468
1493
|
* A coach's month view of a roster athlete's logged sessions
|
|
1469
1494
|
* (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
|
|
1470
1495
|
* ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
|
|
1471
1496
|
* `userId` in each row is the roster athlete, not the calling coach.
|
|
1497
|
+
*
|
|
1498
|
+
* TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
|
|
1499
|
+
* read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
|
|
1472
1500
|
*/
|
|
1473
|
-
function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
|
|
1474
|
-
|
|
1501
|
+
async function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
|
|
1502
|
+
const res = await client.request("GET", `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`);
|
|
1503
|
+
const label = `Coach athlete calendar summary for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}`;
|
|
1504
|
+
if (res.ok) {
|
|
1505
|
+
if (Array.isArray(res.data)) return res.data;
|
|
1506
|
+
throw new Error(`${label} returned an unexpected response shape.`);
|
|
1507
|
+
}
|
|
1508
|
+
const message = trainHeroicApiErrorMessage(label, res.status, res.data);
|
|
1509
|
+
if (res.status === 500) throw new CoachMonthSummaryError(`${message.endsWith(".") ? message : `${message}.`} TrainHeroic's month summary fails for some athletes whose date-range workout read still answers; read the same dates through the date-range read.`, res.status);
|
|
1510
|
+
throw new CoachMonthSummaryError(message, res.status);
|
|
1475
1511
|
}
|
|
1476
1512
|
/**
|
|
1477
1513
|
* Resolve a roster athlete's coach-writable calendar program id
|
|
@@ -1512,8 +1548,7 @@ async function resolveBuildProgramId(client, args) {
|
|
|
1512
1548
|
const [y, m] = parseWorkoutDate(args.date);
|
|
1513
1549
|
return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
|
|
1514
1550
|
}
|
|
1515
|
-
|
|
1516
|
-
//#region src/exercise-set-payload.ts
|
|
1551
|
+
// src/exercise-set-payload.ts
|
|
1517
1552
|
function slotData(exercise, key) {
|
|
1518
1553
|
const value = exercise?.[key];
|
|
1519
1554
|
return value === void 0 || value === null ? "" : String(value);
|
|
@@ -1581,8 +1616,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
|
|
|
1581
1616
|
body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
|
|
1582
1617
|
return body;
|
|
1583
1618
|
}
|
|
1584
|
-
|
|
1585
|
-
//#region src/athlete-set-write.ts
|
|
1619
|
+
// src/athlete-set-write.ts
|
|
1586
1620
|
const WRITE_CONCURRENCY = 4;
|
|
1587
1621
|
/**
|
|
1588
1622
|
* Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
|
|
@@ -2214,8 +2248,7 @@ async function logSessionForAthlete(client, args) {
|
|
|
2214
2248
|
sets
|
|
2215
2249
|
};
|
|
2216
2250
|
}
|
|
2217
|
-
|
|
2218
|
-
//#region src/util.ts
|
|
2251
|
+
// src/util.ts
|
|
2219
2252
|
/**
|
|
2220
2253
|
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
2221
2254
|
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
@@ -2230,8 +2263,7 @@ function definedProps(obj) {
|
|
|
2230
2263
|
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
|
|
2231
2264
|
return result;
|
|
2232
2265
|
}
|
|
2233
|
-
|
|
2234
|
-
//#region src/athlete-workout-note.ts
|
|
2266
|
+
// src/athlete-workout-note.ts
|
|
2235
2267
|
/**
|
|
2236
2268
|
* PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
|
|
2237
2269
|
* workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
|
|
@@ -2261,8 +2293,7 @@ async function setAthleteWorkoutNote(client, args) {
|
|
|
2261
2293
|
rpe: coerceInt(data.rpe) ?? (args.rpe !== void 0 ? args.rpe : null)
|
|
2262
2294
|
};
|
|
2263
2295
|
}
|
|
2264
|
-
|
|
2265
|
-
//#region src/athlete-exercise-note.ts
|
|
2296
|
+
// src/athlete-exercise-note.ts
|
|
2266
2297
|
/**
|
|
2267
2298
|
* PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
|
|
2268
2299
|
* "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
|
|
@@ -2283,8 +2314,7 @@ async function setAthleteExerciseNote(client, args) {
|
|
|
2283
2314
|
notes: typeof data.notes === "string" ? data.notes : args.notes
|
|
2284
2315
|
};
|
|
2285
2316
|
}
|
|
2286
|
-
|
|
2287
|
-
//#region src/workout-export.ts
|
|
2317
|
+
// src/workout-export.ts
|
|
2288
2318
|
const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
|
|
2289
2319
|
/** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
|
|
2290
2320
|
function workoutsToJson(workouts) {
|
|
@@ -2409,8 +2439,7 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
|
|
|
2409
2439
|
filename: `${base}.${meta.extension}`
|
|
2410
2440
|
};
|
|
2411
2441
|
}
|
|
2412
|
-
|
|
2413
|
-
//#region src/workout-encode.ts
|
|
2442
|
+
// src/workout-encode.ts
|
|
2414
2443
|
const LEADERBOARD_TYPE = {
|
|
2415
2444
|
completion: 0,
|
|
2416
2445
|
"for completion": 0,
|
|
@@ -2584,7 +2613,7 @@ function makeExercise(ex, workoutSetId, order, key) {
|
|
|
2584
2613
|
param2Type = ex.param_2_type ?? 1;
|
|
2585
2614
|
param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
|
|
2586
2615
|
} else {
|
|
2587
|
-
param2Type = 0;
|
|
2616
|
+
param2Type = ex.param_2_type ?? 0;
|
|
2588
2617
|
param2Values = null;
|
|
2589
2618
|
}
|
|
2590
2619
|
const entry = {
|
|
@@ -2646,9 +2675,6 @@ function buildBlockPayload(blocks, workoutId) {
|
|
|
2646
2675
|
};
|
|
2647
2676
|
});
|
|
2648
2677
|
}
|
|
2649
|
-
function unitOr(t) {
|
|
2650
|
-
return unitLabel(t) ?? "?";
|
|
2651
|
-
}
|
|
2652
2678
|
const UNIT_ALIASES = {
|
|
2653
2679
|
rep: "reps",
|
|
2654
2680
|
reps: "reps",
|
|
@@ -2686,74 +2712,178 @@ function statedUnit(value, label) {
|
|
|
2686
2712
|
if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
|
|
2687
2713
|
return normalized;
|
|
2688
2714
|
}
|
|
2689
|
-
|
|
2715
|
+
/** TrainHeroic param type codes keyed by their unit label (`sec` and `in` each name two). */
|
|
2716
|
+
const TYPES_BY_UNIT = (() => {
|
|
2717
|
+
const map = /* @__PURE__ */ new Map();
|
|
2718
|
+
for (const [code, unit] of Object.entries(PARAM_UNIT)) if (unit !== null) map.set(unit, [...map.get(unit) ?? [], Number(code)]);
|
|
2719
|
+
return map;
|
|
2720
|
+
})();
|
|
2721
|
+
/**
|
|
2722
|
+
* Pick the param type a populated slot is written with. An explicit `param_N_type` wins and
|
|
2723
|
+
* must agree with the stated unit. Otherwise the exercise's library default is kept when it
|
|
2724
|
+
* already has the stated unit, and any other unit maps to its own type code.
|
|
2725
|
+
*/
|
|
2726
|
+
function resolveSlotType(label, slot, stated, explicit, libraryDefault) {
|
|
2727
|
+
const field = slot === 1 ? "primaryUnit" : "secondaryUnit";
|
|
2690
2728
|
if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
|
|
2691
2729
|
const intended = statedUnit(stated, `${label} / ${field}`);
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
}
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
if (
|
|
2700
|
-
|
|
2701
|
-
}
|
|
2702
|
-
/**
|
|
2703
|
-
|
|
2730
|
+
if (explicit !== void 0) {
|
|
2731
|
+
if (unitLabel(explicit) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param_${slot}_type ${explicit} (${unitLabel(explicit) ?? "unset"}).`);
|
|
2732
|
+
return explicit;
|
|
2733
|
+
}
|
|
2734
|
+
if (libraryDefault !== null && unitLabel(libraryDefault) === intended) return libraryDefault;
|
|
2735
|
+
const [only, ...others] = TYPES_BY_UNIT.get(intended) ?? [];
|
|
2736
|
+
if (only === void 0) throw new Error(`${label}: ${field} ${intended} has no TrainHeroic param type.`);
|
|
2737
|
+
if (others.length === 0) return only;
|
|
2738
|
+
throw new Error(`${label}: ${field} ${intended} matches TrainHeroic param types ${[only, ...others].join(" and ")}; set param_${slot}_type to choose one.`);
|
|
2739
|
+
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Return a copy of `ex` with `param_1_type` and `param_2_type` set to the types the encoder
|
|
2742
|
+
* writes. A slot without values always gets the library default (an explicit type there is
|
|
2743
|
+
* ignored, and `resolveExerciseUnits` warns about it), so only a slot with values can carry a
|
|
2744
|
+
* type that differs from the library.
|
|
2745
|
+
*/
|
|
2746
|
+
function withResolvedParamTypes(label, ex, defaults) {
|
|
2747
|
+
const param1 = ex.reps === void 0 ? defaults.param1 ?? 3 : resolveSlotType(label, 1, ex.primaryUnit, ex.param_1_type, defaults.param1);
|
|
2748
|
+
const param2 = ex.weight === void 0 ? defaults.param2 ?? 0 : resolveSlotType(label, 2, ex.secondaryUnit, ex.param_2_type, defaults.param2);
|
|
2749
|
+
return {
|
|
2750
|
+
...ex,
|
|
2751
|
+
param_1_type: param1,
|
|
2752
|
+
param_2_type: param2
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
/**
|
|
2756
|
+
* The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
|
|
2757
|
+
* other than the library default. This is the one definition of a unit override: the advisory
|
|
2758
|
+
* notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
|
|
2759
|
+
* exactly these types.
|
|
2760
|
+
*/
|
|
2761
|
+
function overriddenSlots(ex, defaults) {
|
|
2762
|
+
const overridden = [];
|
|
2763
|
+
if (ex.reps !== void 0 && ex.param_1_type !== defaults.param1) overridden.push(1);
|
|
2764
|
+
if (ex.weight !== void 0 && ex.param_2_type !== defaults.param2) overridden.push(2);
|
|
2765
|
+
return overridden;
|
|
2766
|
+
}
|
|
2767
|
+
/** A param type's unit label for advisory text; "unset" for a slot without a type. */
|
|
2768
|
+
function unitName(type) {
|
|
2769
|
+
return unitLabel(type) ?? "unset";
|
|
2770
|
+
}
|
|
2771
|
+
/**
|
|
2772
|
+
* Describe how a resolved exercise's units relate to its library defaults, and flag spec
|
|
2773
|
+
* fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
|
|
2774
|
+
* (from `resolveExerciseUnits`).
|
|
2775
|
+
*/
|
|
2776
|
+
function unitAdvisory(label, ex, defaults) {
|
|
2704
2777
|
const notes = [];
|
|
2705
2778
|
const warnings = [];
|
|
2706
|
-
const u =
|
|
2707
|
-
const label = `${blockTitle} / ${ex.title ?? ex.id}`;
|
|
2779
|
+
const u = unitName;
|
|
2708
2780
|
if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
|
|
2709
|
-
const
|
|
2710
|
-
if (
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
if (ex.weight !== void 0 && ex.weight !== null) {
|
|
2715
|
-
const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
|
|
2716
|
-
const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
|
|
2717
|
-
if (sentP2 !== effP2) {
|
|
2718
|
-
if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
|
|
2719
|
-
else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
|
|
2720
|
-
}
|
|
2721
|
-
}
|
|
2781
|
+
const overrides = overriddenSlots(ex, defaults);
|
|
2782
|
+
if (overrides.includes(1)) notes.push(`${label}: primary values are in ${u(ex.param_1_type)}, set on this session in place of the exercise's default ${u(defaults.param1)}.`);
|
|
2783
|
+
else if (ex.reps !== void 0 && ex.param_1_type !== 3) notes.push(`${label}: values are in ${u(ex.param_1_type)} (the exercise's default primary unit).`);
|
|
2784
|
+
const addedLoad = ex.param_2_type === 1 && (defaults.param2 === 0 || defaults.param2 === null);
|
|
2785
|
+
if (overrides.includes(2) && !addedLoad) notes.push(`${label}: secondary values are in ${u(ex.param_2_type)}, set on this session in place of the exercise's default ${u(defaults.param2)}.`);
|
|
2722
2786
|
return {
|
|
2723
2787
|
notes,
|
|
2724
2788
|
warnings
|
|
2725
2789
|
};
|
|
2726
2790
|
}
|
|
2791
|
+
/** Warn about explicit param types on slots without values, which the encoder ignores. */
|
|
2792
|
+
function ignoredTypeWarnings(label, ex) {
|
|
2793
|
+
const warnings = [];
|
|
2794
|
+
if (ex.reps === void 0 && ex.param_1_type !== void 0) warnings.push(`${label}: param_1_type ${ex.param_1_type} is ignored because reps has no values; the slot keeps the exercise's default.`);
|
|
2795
|
+
if (ex.weight === void 0 && ex.param_2_type !== void 0) warnings.push(`${label}: param_2_type ${ex.param_2_type} is ignored because weight has no values; the slot keeps the exercise's default.`);
|
|
2796
|
+
return warnings;
|
|
2797
|
+
}
|
|
2727
2798
|
/**
|
|
2728
|
-
*
|
|
2729
|
-
*
|
|
2730
|
-
*
|
|
2799
|
+
* Resolve every exercise's param types against current TrainHeroic exercise data and collect
|
|
2800
|
+
* non-blocking advisories. Throws, before anything is written, when a populated slot has no
|
|
2801
|
+
* stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
|
|
2802
|
+
* returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
|
|
2731
2803
|
*/
|
|
2732
|
-
async function
|
|
2733
|
-
const
|
|
2734
|
-
block: b,
|
|
2735
|
-
ex
|
|
2736
|
-
})));
|
|
2737
|
-
const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
|
|
2804
|
+
async function resolveExerciseUnits(blocks, index) {
|
|
2805
|
+
const ids = [...new Set(blocks.flatMap((b) => b.exercises.map((ex) => Number(ex.id))).filter(Number.isFinite))];
|
|
2738
2806
|
const defaultsById = await index.currentDefaultsMany(ids);
|
|
2739
2807
|
const notes = [];
|
|
2740
2808
|
const warnings = [];
|
|
2741
|
-
pairs.forEach((p) => {
|
|
2742
|
-
const def = defaultsById.get(Number(p.ex.id));
|
|
2743
|
-
if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
|
|
2744
|
-
validateExerciseUnits(p.block.title, p.ex, def);
|
|
2745
|
-
const advisory = unitAdvisory(p.block.title, p.ex, def);
|
|
2746
|
-
notes.push(...advisory.notes);
|
|
2747
|
-
warnings.push(...advisory.warnings);
|
|
2748
|
-
});
|
|
2749
2809
|
return {
|
|
2750
|
-
|
|
2751
|
-
|
|
2810
|
+
blocks: blocks.map((block) => ({
|
|
2811
|
+
...block,
|
|
2812
|
+
exercises: block.exercises.map((ex) => {
|
|
2813
|
+
const label = `${block.title} / ${ex.title ?? ex.id}`;
|
|
2814
|
+
const def = defaultsById.get(Number(ex.id));
|
|
2815
|
+
if (!def) throw new Error(`${label}: exercise id ${ex.id} was not found in the library.`);
|
|
2816
|
+
const typed = withResolvedParamTypes(label, ex, def);
|
|
2817
|
+
const advisory = unitAdvisory(label, typed, def);
|
|
2818
|
+
notes.push(...advisory.notes);
|
|
2819
|
+
warnings.push(...ignoredTypeWarnings(label, ex), ...advisory.warnings);
|
|
2820
|
+
return typed;
|
|
2821
|
+
})
|
|
2822
|
+
})),
|
|
2823
|
+
defaultsById,
|
|
2824
|
+
advisories: {
|
|
2825
|
+
notes,
|
|
2826
|
+
warnings
|
|
2827
|
+
}
|
|
2752
2828
|
};
|
|
2753
2829
|
}
|
|
2754
|
-
|
|
2755
|
-
|
|
2830
|
+
/**
|
|
2831
|
+
* Validate units and collect advisories without writing a workout. This is the preview entry
|
|
2832
|
+
* point; `resolveExerciseUnits` also returns the resolved blocks that `buildSession` writes.
|
|
2833
|
+
*/
|
|
2834
|
+
async function collectAdvisories(blocks, index) {
|
|
2835
|
+
return (await resolveExerciseUnits(blocks, index)).advisories;
|
|
2836
|
+
}
|
|
2837
|
+
// src/workout-session.ts
|
|
2756
2838
|
const EXERCISE_SAVE_CONCURRENCY = 4;
|
|
2839
|
+
const SAVE_EXERCISES_PATH = "/2.0/coach/calendar/saveWorkoutSetExercises";
|
|
2840
|
+
/**
|
|
2841
|
+
* Pair each sent entry with the row TrainHeroic returned for it. A block's rows are matched on
|
|
2842
|
+
* `order` (unique within one block's payload) and must carry the same `exercise_id` and an id.
|
|
2843
|
+
* Throws when the response is not a row array or a row is missing, because the caller cannot
|
|
2844
|
+
* then confirm which units TrainHeroic stored.
|
|
2845
|
+
*/
|
|
2846
|
+
function matchSavedRows(saves, response, pwId) {
|
|
2847
|
+
if (!Array.isArray(response)) throw new Error(`saveWorkoutSetExercises returned an unexpected response shape for draft session ${pwId}.`);
|
|
2848
|
+
const rows = response.filter((row) => typeof row === "object" && row !== null);
|
|
2849
|
+
return saves.map((save) => {
|
|
2850
|
+
const row = rows.find((r) => coerceInt(r.order) === coerceInt(save.entry.order) && coerceInt(r.exercise_id) === coerceInt(save.entry.exercise_id));
|
|
2851
|
+
const id = coerceInt(row?.id);
|
|
2852
|
+
if (row === void 0 || id === null) throw new Error(`saveWorkoutSetExercises returned no row for exercise ${String(save.entry.exercise_id)} (order ${String(save.entry.order)}) on draft session ${pwId}.`);
|
|
2853
|
+
return {
|
|
2854
|
+
save,
|
|
2855
|
+
row,
|
|
2856
|
+
id
|
|
2857
|
+
};
|
|
2858
|
+
});
|
|
2859
|
+
}
|
|
2860
|
+
/** True when the stored row holds the requested type in every overridden slot. */
|
|
2861
|
+
function keepsOverrides(save, row) {
|
|
2862
|
+
return save.overrides.every((slot) => coerceInt(row[`param_${slot}_type`]) === coerceInt(save.entry[`param_${slot}_type`]));
|
|
2863
|
+
}
|
|
2864
|
+
/**
|
|
2865
|
+
* Save one block's exercises. TrainHeroic stores a newly inserted row with the exercise's
|
|
2866
|
+
* library param types whatever the request says, and keeps the requested types when the same
|
|
2867
|
+
* row is saved again with its `id`; the coach web app's unit picker saves single rows by id
|
|
2868
|
+
* the same way. So each row with an overridden slot (say %max load on a pounds lift) that the
|
|
2869
|
+
* insert stored in the library type is saved a second time by id. Throws when the second save
|
|
2870
|
+
* still does not hold the requested types, because the values would render in the wrong unit.
|
|
2871
|
+
*/
|
|
2872
|
+
async function saveBlockExercises(client, pwId, saves) {
|
|
2873
|
+
const corrections = matchSavedRows(saves, await req(client, "POST", SAVE_EXERCISES_PATH, saves.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row)).map(({ save, id }) => ({
|
|
2874
|
+
entry: {
|
|
2875
|
+
...save.entry,
|
|
2876
|
+
id
|
|
2877
|
+
},
|
|
2878
|
+
overrides: save.overrides
|
|
2879
|
+
}));
|
|
2880
|
+
if (corrections.length === 0) return;
|
|
2881
|
+
const unkept = matchSavedRows(corrections, await req(client, "POST", SAVE_EXERCISES_PATH, corrections.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row));
|
|
2882
|
+
if (unkept.length > 0) {
|
|
2883
|
+
const names = unkept.map(({ save, row }) => typeof row.title === "string" && row.title !== "" ? row.title : `exercise ${String(save.entry.exercise_id)}`).join(", ");
|
|
2884
|
+
throw new Error(`TrainHeroic did not keep the requested units for ${names} on draft session ${pwId}. Remove the draft or correct those exercises in the coach app.`);
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2757
2887
|
/**
|
|
2758
2888
|
* Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
|
|
2759
2889
|
* on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
|
|
@@ -2782,8 +2912,9 @@ async function buildSession(client, opts) {
|
|
|
2782
2912
|
const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
|
|
2783
2913
|
const splitSummary = setSplitSummary(validatedBlocks);
|
|
2784
2914
|
if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
|
|
2785
|
-
const
|
|
2786
|
-
const
|
|
2915
|
+
const resolved = await resolveExerciseUnits(validatedBlocks, opts.index);
|
|
2916
|
+
const advisories = resolved.advisories;
|
|
2917
|
+
const blocks = splitSummary === null ? resolved.blocks : splitOversizedBlocks(resolved.blocks);
|
|
2787
2918
|
const sess = await req(client, "POST", createPath(opts), {});
|
|
2788
2919
|
checkResponse(sessionCreateResponseSchema, sess, "session create");
|
|
2789
2920
|
const workoutId = Number(sess.workout_id);
|
|
@@ -2796,9 +2927,13 @@ async function buildSession(client, opts) {
|
|
|
2796
2927
|
if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
|
|
2797
2928
|
return block.exercises.map((ex, j) => {
|
|
2798
2929
|
counter += 1;
|
|
2799
|
-
|
|
2930
|
+
const defaults = resolved.defaultsById.get(Number(ex.id));
|
|
2931
|
+
return {
|
|
2932
|
+
entry: makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`),
|
|
2933
|
+
overrides: defaults === void 0 ? [] : overriddenSlots(ex, defaults)
|
|
2934
|
+
};
|
|
2800
2935
|
});
|
|
2801
|
-
}).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (
|
|
2936
|
+
}).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (saves) => saveBlockExercises(client, pwId, saves));
|
|
2802
2937
|
if (opts.instruction !== void 0 && opts.instruction !== "") {
|
|
2803
2938
|
const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
|
|
2804
2939
|
await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
|
|
@@ -2847,6 +2982,7 @@ async function readSession(client, programId, date, pwId) {
|
|
|
2847
2982
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2848
2983
|
return {
|
|
2849
2984
|
pwId,
|
|
2985
|
+
workoutId: coerceInt(pw.workout_id),
|
|
2850
2986
|
date: `${str$1(pw.year)}-${str$1(pw.month).padStart(2, "0")}-${str$1(pw.day).padStart(2, "0")}`,
|
|
2851
2987
|
published: pw.published,
|
|
2852
2988
|
instruction: str$1(pw.instruction),
|
|
@@ -2884,8 +3020,7 @@ function readExercise(ex) {
|
|
|
2884
3020
|
instruction: str$1(ex.instruction)
|
|
2885
3021
|
};
|
|
2886
3022
|
}
|
|
2887
|
-
|
|
2888
|
-
//#region src/coach.ts
|
|
3023
|
+
// src/coach.ts
|
|
2889
3024
|
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
2890
3025
|
const PROGRAM_KINDS = ["calendar", "fixed"];
|
|
2891
3026
|
/**
|
|
@@ -3271,9 +3406,26 @@ async function requestAnalytics(client, args) {
|
|
|
3271
3406
|
body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
|
|
3272
3407
|
}
|
|
3273
3408
|
const res = await client.request("POST", spec.path, { body });
|
|
3274
|
-
if (!res.ok)
|
|
3409
|
+
if (!res.ok) {
|
|
3410
|
+
const message = trainHeroicApiErrorMessage(`Analytics ${args.metric}`, res.status, res.data);
|
|
3411
|
+
throw new Error(withHint(message, analyticsErrorHint(res.data)));
|
|
3412
|
+
}
|
|
3275
3413
|
return res.data;
|
|
3276
3414
|
}
|
|
3415
|
+
/**
|
|
3416
|
+
* Explain TrainHeroic's terse analytics rejections so the caller can fix its input.
|
|
3417
|
+
* lift-1rm-history answers "Invalid exercise id" for any exercise that is not a weighted lift
|
|
3418
|
+
* (verified with Run, Push-Up, and an unknown id; Back Squat succeeds).
|
|
3419
|
+
*/
|
|
3420
|
+
function analyticsErrorHint(responseBody) {
|
|
3421
|
+
if (typeof responseBody === "string" && responseBody.includes("Invalid exercise id")) return "exerciseId must be a weighted lift such as Back Squat (id 1); bodyweight, distance, and unknown exercises are rejected.";
|
|
3422
|
+
return null;
|
|
3423
|
+
}
|
|
3424
|
+
/** Append a sentence of guidance to an error message that may or may not end in a period. */
|
|
3425
|
+
function withHint(message, hint) {
|
|
3426
|
+
if (hint === null) return message;
|
|
3427
|
+
return `${message.endsWith(".") ? message : `${message}.`} ${hint}`;
|
|
3428
|
+
}
|
|
3277
3429
|
function reportRows(report) {
|
|
3278
3430
|
if (report === null || typeof report !== "object") return null;
|
|
3279
3431
|
const rows = report.rows;
|
|
@@ -3413,10 +3565,31 @@ async function createSessionTemplate(client, args) {
|
|
|
3413
3565
|
if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
|
|
3414
3566
|
return res.data;
|
|
3415
3567
|
}
|
|
3568
|
+
/**
|
|
3569
|
+
* Copy an existing calendar session, with its blocks and exercises, into the coach's session
|
|
3570
|
+
* library as a new template
|
|
3571
|
+
* (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
|
|
3572
|
+
* the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
|
|
3573
|
+
* the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
|
|
3574
|
+
* has no `id`, or when the two ids are swapped.
|
|
3575
|
+
*/
|
|
3576
|
+
async function saveSessionAsTemplate(client, args) {
|
|
3577
|
+
const title = args.title.trim();
|
|
3578
|
+
if (title === "") throw new Error("Session template title must not be blank.");
|
|
3579
|
+
const res = await client.request("POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${args.workoutId}`, { body: {
|
|
3580
|
+
id: args.pwId,
|
|
3581
|
+
title
|
|
3582
|
+
} });
|
|
3583
|
+
if (!res.ok) {
|
|
3584
|
+
const message = trainHeroicApiErrorMessage(`Saving session ${args.pwId} (workout ${args.workoutId}) as a template`, res.status, res.data);
|
|
3585
|
+
throw new Error(withHint(message, "Check that workoutId and pwId belong to the same session; a session read-back returns both."));
|
|
3586
|
+
}
|
|
3587
|
+
if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template save response is missing an id.");
|
|
3588
|
+
return res.data;
|
|
3589
|
+
}
|
|
3416
3590
|
/** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
|
|
3417
3591
|
const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
|
|
3418
|
-
|
|
3419
|
-
//#region src/main-lifts.ts
|
|
3592
|
+
// src/main-lifts.ts
|
|
3420
3593
|
/**
|
|
3421
3594
|
* The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
|
|
3422
3595
|
* first family that matches, so the more specific / easily-confused families come before the broad
|
|
@@ -3628,8 +3801,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
|
|
|
3628
3801
|
};
|
|
3629
3802
|
});
|
|
3630
3803
|
}
|
|
3631
|
-
|
|
3632
|
-
//#region src/messaging.ts
|
|
3804
|
+
// src/messaging.ts
|
|
3633
3805
|
const BUCKETS = [
|
|
3634
3806
|
["team", "teams"],
|
|
3635
3807
|
["athlete", "athletes"],
|
|
@@ -3684,8 +3856,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
|
|
|
3684
3856
|
if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
|
|
3685
3857
|
return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
|
|
3686
3858
|
}
|
|
3687
|
-
|
|
3688
|
-
//#region src/library-cache.ts
|
|
3859
|
+
// src/library-cache.ts
|
|
3689
3860
|
/** In-memory cache (no persistence). The default when none is supplied. */
|
|
3690
3861
|
var MemoryLibraryCache = class {
|
|
3691
3862
|
#snapshot = null;
|
|
@@ -3696,8 +3867,7 @@ var MemoryLibraryCache = class {
|
|
|
3696
3867
|
this.#snapshot = snapshot;
|
|
3697
3868
|
}
|
|
3698
3869
|
};
|
|
3699
|
-
|
|
3700
|
-
//#region src/exercise-index.ts
|
|
3870
|
+
// src/exercise-index.ts
|
|
3701
3871
|
const LIBRARY_PATH = "/v5/exerciseLibrary/all";
|
|
3702
3872
|
const CREATE_PATH = "/2.0/coach/exercise/create";
|
|
3703
3873
|
const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
|
|
@@ -3903,5 +4073,4 @@ var ExerciseLibrary = class {
|
|
|
3903
4073
|
};
|
|
3904
4074
|
}
|
|
3905
4075
|
};
|
|
3906
|
-
|
|
3907
|
-
export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, 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, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchCurrentExerciseDefaults, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, trainHeroicApiErrorMessage, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
|
4076
|
+
export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, CoachMonthSummaryError, 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, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, TrainHeroicUnavailableError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchCurrentExerciseDefaults, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, isTrainHeroicUnavailableStatus, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, overriddenSlots, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveExerciseUnits, resolveLeaderboard, saveSessionAsTemplate, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, trainHeroicApiErrorMessage, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/library-cache.d.ts
|
|
2
1
|
/** A persisted snapshot of the exercise library: the raw rows plus when they were fetched. */
|
|
3
2
|
type LibrarySnapshot = {
|
|
4
3
|
fetchedAt: number;
|
|
@@ -18,5 +17,4 @@ declare class MemoryLibraryCache implements LibraryCache {
|
|
|
18
17
|
load(): Promise<LibrarySnapshot | null>;
|
|
19
18
|
save(snapshot: LibrarySnapshot): Promise<void>;
|
|
20
19
|
}
|
|
21
|
-
//#endregion
|
|
22
20
|
export { LibrarySnapshot as n, MemoryLibraryCache as r, LibraryCache as t };
|
package/dist/node.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { n as LibrarySnapshot, t as LibraryCache } from "./library-cache-
|
|
2
|
-
//#region src/node.d.ts
|
|
1
|
+
import { n as LibrarySnapshot, t as LibraryCache } from "./library-cache-TkOsfh5m.mjs";
|
|
3
2
|
/** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
|
|
4
3
|
export declare function defaultCachePath(): string;
|
|
5
4
|
/** Persists the exercise library to a JSON file. */
|
|
@@ -8,5 +7,4 @@ export declare class JsonFileLibraryCache implements LibraryCache {
|
|
|
8
7
|
constructor(path?: string);
|
|
9
8
|
load(): Promise<LibrarySnapshot | null>;
|
|
10
9
|
save(snapshot: LibrarySnapshot): Promise<void>;
|
|
11
|
-
}
|
|
12
|
-
//#endregion
|
|
10
|
+
}
|
package/dist/node.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import process from "node:process";
|
|
5
|
-
|
|
5
|
+
// src/node.ts
|
|
6
6
|
/** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
|
|
7
7
|
function defaultCachePath() {
|
|
8
8
|
return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
|
|
@@ -25,5 +25,4 @@ var JsonFileLibraryCache = class {
|
|
|
25
25
|
await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
|
|
26
26
|
}
|
|
27
27
|
};
|
|
28
|
-
//#endregion
|
|
29
28
|
export { JsonFileLibraryCache, defaultCachePath };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,14 +26,14 @@
|
|
|
26
26
|
"dist"
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"es-toolkit": "^1.
|
|
30
|
-
"zod": "^4.6.
|
|
31
|
-
"@trainheroic-unofficial/dto": "4.
|
|
29
|
+
"es-toolkit": "^1.53.2",
|
|
30
|
+
"zod": "^4.6.7",
|
|
31
|
+
"@trainheroic-unofficial/dto": "4.3.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@types/node": "^26.6.
|
|
35
|
-
"tsdown": "^0.23.
|
|
36
|
-
"vitest": "^5.0
|
|
34
|
+
"@types/node": "^26.6.6",
|
|
35
|
+
"tsdown": "^0.23.7",
|
|
36
|
+
"vitest": "^5.1.0"
|
|
37
37
|
},
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "tsdown",
|