@trainheroic-unofficial/js 3.1.0 → 3.2.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 +11 -1
- package/dist/index.d.mts +78 -4
- package/dist/index.mjs +189 -22
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -161,12 +161,22 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
|
|
|
161
161
|
- **Messaging.** Tools for conversation streams: listing them, reading a stream, and
|
|
162
162
|
building or sending or deleting a comment.
|
|
163
163
|
|
|
164
|
+
`createProgram(client, { kind, name })` creates a standalone `calendar` or `fixed` program and
|
|
165
|
+
returns both `containerId` (the id in `GET /1.0/coach/programs`) and `programId` (the id used by
|
|
166
|
+
program detail and workout writes). TrainHeroic may replace the requested name; inspect the
|
|
167
|
+
returned `title` and `nameApplied`. Creation is not idempotent, so do not blindly retry an
|
|
168
|
+
uncertain result. `deleteProgram(client, programId)` removes it via `DELETE /v5/programs/{id}`
|
|
169
|
+
and accepts either id (a container id is resolved to `group_program` first).
|
|
170
|
+
|
|
164
171
|
## Working with exercises
|
|
165
172
|
|
|
166
173
|
`ExerciseLibrary` loads the full library once, caches it, and answers name lookups and fuzzy
|
|
167
174
|
search against the in-memory copy. By default it caches in memory; pass a `JsonFileLibraryCache`
|
|
168
175
|
from `./node` to persist between runs (it writes to `defaultCachePath()`,
|
|
169
|
-
`~/.trainheroic/library.json`, unless you pass a path).
|
|
176
|
+
`~/.trainheroic/library.json`, unless you pass a path). `create` / `update` / `remove` write through to
|
|
177
|
+
TrainHeroic (`POST /2.0/coach/exercise/create`, `POST /2.0/coach/exercise/update/{id}`,
|
|
178
|
+
`DELETE /v5/exercises/{id}`); `recordDelete`
|
|
179
|
+
only drops the cached row.
|
|
170
180
|
|
|
171
181
|
```ts
|
|
172
182
|
import { ExerciseLibrary } from "@trainheroic-unofficial/js";
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
|
|
2
|
-
import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
|
|
2
|
+
import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
|
|
3
3
|
import { ZodType } from "zod";
|
|
4
4
|
export * from "@trainheroic-unofficial/dto";
|
|
5
5
|
//#region src/http-error.d.ts
|
|
@@ -44,6 +44,8 @@ type ApiBase = "coach" | "apis";
|
|
|
44
44
|
type RequestOptions = {
|
|
45
45
|
body?: unknown;
|
|
46
46
|
base?: ApiBase;
|
|
47
|
+
/** Final non-2xx statuses the caller handles as part of normal control flow. */
|
|
48
|
+
expectedStatuses?: readonly number[];
|
|
47
49
|
};
|
|
48
50
|
type ClientResult<T = unknown> = {
|
|
49
51
|
status: number;
|
|
@@ -60,8 +62,9 @@ type ClientOptions = {
|
|
|
60
62
|
onSession?: (sessionId: string) => void;
|
|
61
63
|
/**
|
|
62
64
|
* Called once when a login or API request finishes with a non-2xx response. Transient 401/403
|
|
63
|
-
* API responses that succeed after the built-in re-login
|
|
64
|
-
*
|
|
65
|
+
* API responses that succeed after the built-in re-login and final statuses declared through
|
|
66
|
+
* `RequestOptions.expectedStatuses` are not reported. The callback is best-effort: telemetry
|
|
67
|
+
* failures never change the API result returned to the caller.
|
|
65
68
|
*/
|
|
66
69
|
onHttpError?: TrainHeroicHttpErrorHandler;
|
|
67
70
|
};
|
|
@@ -175,6 +178,10 @@ interface ExerciseIndex {
|
|
|
175
178
|
get(id: number): Promise<Record<string, unknown> | null>;
|
|
176
179
|
defaultsMany(ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
|
|
177
180
|
create(body: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
181
|
+
/** POST an update to a custom exercise on TrainHeroic, then refresh the mirror row. */
|
|
182
|
+
update(id: number, body: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
183
|
+
/** DELETE the custom exercise on TrainHeroic, then drop it from the mirror. */
|
|
184
|
+
remove(id: number): Promise<void>;
|
|
178
185
|
recordDelete(id: number): Promise<void>;
|
|
179
186
|
stats(): Promise<Record<string, unknown>>;
|
|
180
187
|
}
|
|
@@ -206,6 +213,9 @@ declare function fetchRosterActivity(client: TrainHeroicClient, athleteIds: read
|
|
|
206
213
|
declare function fetchAthletePrefs(client: TrainHeroicClient): Promise<AthletePrefs>;
|
|
207
214
|
declare function fetchWorkingMaxes(client: TrainHeroicClient): Promise<AthleteWorkingMax[]>;
|
|
208
215
|
declare function fetchExerciseHistoryList(client: TrainHeroicClient): Promise<ExerciseHistoryListItem[]>;
|
|
216
|
+
declare function fetchRecentExercises(client: TrainHeroicClient): Promise<unknown[]>;
|
|
217
|
+
declare function fetchAthleteCircuits(client: TrainHeroicClient, kind?: "recent" | "history"): Promise<unknown[]>;
|
|
218
|
+
declare function fetchAthleteProgrammingPrograms(client: TrainHeroicClient): Promise<unknown[]>;
|
|
209
219
|
/** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
|
|
210
220
|
declare function searchExerciseHistory(client: TrainHeroicClient, query: string, limit?: number): Promise<ExerciseHistoryListItem[]>;
|
|
211
221
|
declare function fetchExerciseHistoryDetail(client: TrainHeroicClient, exerciseId: number, userId: number): Promise<ExerciseHistoryDetail>;
|
|
@@ -780,6 +790,46 @@ declare function fetchRosterMainLiftPRs(client: TrainHeroicClient, opts?: {
|
|
|
780
790
|
//#endregion
|
|
781
791
|
//#region src/coach.d.ts
|
|
782
792
|
declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
793
|
+
declare const PROGRAM_KINDS: readonly ["calendar", "fixed"];
|
|
794
|
+
type ProgramKind = (typeof PROGRAM_KINDS)[number];
|
|
795
|
+
type CreatedProgram = {
|
|
796
|
+
/** Container/group id returned by list_programs and used by calendar edit/sync endpoints. */
|
|
797
|
+
containerId: number;
|
|
798
|
+
/** Actual program id used by get_program, workout creation, and other program-scoped writes. */
|
|
799
|
+
programId: number;
|
|
800
|
+
/** Title TrainHeroic actually assigned. The current API may ignore the requested name. */
|
|
801
|
+
title: string;
|
|
802
|
+
kind: ProgramKind;
|
|
803
|
+
requestedName: string;
|
|
804
|
+
nameApplied: boolean;
|
|
805
|
+
};
|
|
806
|
+
/**
|
|
807
|
+
* Create a standalone ongoing calendar or fixed-length program.
|
|
808
|
+
*
|
|
809
|
+
* TrainHeroic returns both a container id and the underlying program id. They are deliberately
|
|
810
|
+
* named separately here because `/3.0/coach/program/{containerId}` returns 401, while the
|
|
811
|
+
* `programId` works. This write is not idempotent: callers must not blindly retry an uncertain
|
|
812
|
+
* result. The live API currently accepts `name` but may generate its own title; `nameApplied`
|
|
813
|
+
* reports what happened.
|
|
814
|
+
*/
|
|
815
|
+
declare function createProgram(client: TrainHeroicClient, args: {
|
|
816
|
+
kind: ProgramKind;
|
|
817
|
+
name: string;
|
|
818
|
+
}): Promise<CreatedProgram>;
|
|
819
|
+
type DeletedProgram = {
|
|
820
|
+
/** Actual program id sent to `DELETE /v5/programs/{id}`. */
|
|
821
|
+
programId: number;
|
|
822
|
+
/** Container id when the caller passed a list_programs row id (otherwise null). */
|
|
823
|
+
containerId: number | null;
|
|
824
|
+
};
|
|
825
|
+
/**
|
|
826
|
+
* Delete a standalone program (`DELETE /v5/programs/{programId}`).
|
|
827
|
+
*
|
|
828
|
+
* The live API 401s when the path id is a list_programs container id. Pass either id: this
|
|
829
|
+
* resolves a container to its `group_program` first. Team calendars are not in that list; their
|
|
830
|
+
* program id is deleted as given. This is not idempotent against an unknown failure.
|
|
831
|
+
*/
|
|
832
|
+
declare function deleteProgram(client: TrainHeroicClient, programId: number): Promise<DeletedProgram>;
|
|
783
833
|
/** A roster member as id + display name. */
|
|
784
834
|
type CoachRosterAthlete = {
|
|
785
835
|
id: number;
|
|
@@ -819,6 +869,24 @@ declare function updateTeam(client: TrainHeroicClient, args: {
|
|
|
819
869
|
title?: string;
|
|
820
870
|
groupProgram?: number;
|
|
821
871
|
}): Promise<unknown>;
|
|
872
|
+
type TeamPublishTarget = {
|
|
873
|
+
programId: number;
|
|
874
|
+
} | {
|
|
875
|
+
teamId: number;
|
|
876
|
+
};
|
|
877
|
+
/** Collapse the MCP/CLI XOR flags into a single publish target. */
|
|
878
|
+
declare function teamPublishTarget(ids: {
|
|
879
|
+
programId?: number;
|
|
880
|
+
teamId?: number;
|
|
881
|
+
}): TeamPublishTarget;
|
|
882
|
+
/**
|
|
883
|
+
* Update a team's auto-publish settings (`POST /1.0/coach/team/updatePublishSettings`).
|
|
884
|
+
* The live API 500s on a partial body; it wants the full program object from
|
|
885
|
+
* `GET /3.0/coach/program/{programId}` with `pub_*` fields merged on top.
|
|
886
|
+
*/
|
|
887
|
+
declare function updateTeamPublishSettings(client: TrainHeroicClient, args: TeamPublishTarget & {
|
|
888
|
+
patch: TeamPublishPatch;
|
|
889
|
+
}): Promise<unknown>;
|
|
822
890
|
/**
|
|
823
891
|
* Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
|
|
824
892
|
* The API wants the target date as a structured object (with weekday and an isToday flag),
|
|
@@ -881,6 +949,10 @@ declare function teamVolume(client: TrainHeroicClient, args: {
|
|
|
881
949
|
dateStart: string;
|
|
882
950
|
dateEnd: string;
|
|
883
951
|
}): Promise<TeamVolumeReport>;
|
|
952
|
+
/** Create a reusable session template in the coach library (`POST /v5/sessions/template`). */
|
|
953
|
+
declare function createSessionTemplate(client: TrainHeroicClient, args: SessionTemplateCreate): Promise<Record<string, unknown>>;
|
|
954
|
+
/** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
|
|
955
|
+
declare const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
|
|
884
956
|
//#endregion
|
|
885
957
|
//#region src/util.d.ts
|
|
886
958
|
/**
|
|
@@ -992,8 +1064,10 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
992
1064
|
search(query: string, limit?: number): Promise<ExerciseView[]>;
|
|
993
1065
|
resolve(name: string): Promise<ResolveResult>;
|
|
994
1066
|
create(body: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
1067
|
+
update(id: number, body: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
1068
|
+
remove(id: number): Promise<void>;
|
|
995
1069
|
recordDelete(id: number): Promise<void>;
|
|
996
1070
|
stats(): Promise<Record<string, unknown>>;
|
|
997
1071
|
}
|
|
998
1072
|
//#endregion
|
|
999
|
-
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
|
1073
|
+
export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, DEFAULT_INVITE_MESSAGE, DeletedProgram, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, RequestOptions, ResolvedLift, SESSION_TEMPLATES_LIST_PATH, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TeamPublishTarget, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
|
|
1
|
+
import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programCreateResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
export * from "@trainheroic-unofficial/dto";
|
|
4
4
|
//#region src/http-error.ts
|
|
@@ -149,7 +149,7 @@ var TrainHeroicClient = class {
|
|
|
149
149
|
session = await this.#ensureSession();
|
|
150
150
|
res = await this.#send(method, url, session, options.body);
|
|
151
151
|
}
|
|
152
|
-
if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
|
|
152
|
+
if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
|
|
153
153
|
const text = await res.text();
|
|
154
154
|
let data = text;
|
|
155
155
|
if (text.length > 0) try {
|
|
@@ -480,6 +480,15 @@ function fetchWorkingMaxes(client) {
|
|
|
480
480
|
function fetchExerciseHistoryList(client) {
|
|
481
481
|
return getArray$1(client, "/v5/users/exercises/history", "athlete exercise history list");
|
|
482
482
|
}
|
|
483
|
+
function fetchRecentExercises(client) {
|
|
484
|
+
return getArray$1(client, "/v5/users/exercises/recent", "athlete recent exercises");
|
|
485
|
+
}
|
|
486
|
+
function fetchAthleteCircuits(client, kind = "recent") {
|
|
487
|
+
return getArray$1(client, `/v5/users/circuits/${kind}`, `athlete ${kind} circuits`);
|
|
488
|
+
}
|
|
489
|
+
function fetchAthleteProgrammingPrograms(client) {
|
|
490
|
+
return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
|
|
491
|
+
}
|
|
483
492
|
/** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
|
|
484
493
|
async function searchExerciseHistory(client, query, limit = 20) {
|
|
485
494
|
return rankSearch(await fetchExerciseHistoryList(client), query, limit);
|
|
@@ -1860,6 +1869,22 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
|
|
|
1860
1869
|
};
|
|
1861
1870
|
}
|
|
1862
1871
|
//#endregion
|
|
1872
|
+
//#region src/util.ts
|
|
1873
|
+
/**
|
|
1874
|
+
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
1875
|
+
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
1876
|
+
* `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
|
|
1877
|
+
* optional ones lose `undefined` from their value type.
|
|
1878
|
+
*
|
|
1879
|
+
* Example:
|
|
1880
|
+
* definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
|
|
1881
|
+
*/
|
|
1882
|
+
function definedProps(obj) {
|
|
1883
|
+
const result = {};
|
|
1884
|
+
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
|
|
1885
|
+
return result;
|
|
1886
|
+
}
|
|
1887
|
+
//#endregion
|
|
1863
1888
|
//#region src/workout-encode.ts
|
|
1864
1889
|
const LEADERBOARD_TYPE = {
|
|
1865
1890
|
completion: 0,
|
|
@@ -2219,6 +2244,84 @@ function readExercise(ex) {
|
|
|
2219
2244
|
//#endregion
|
|
2220
2245
|
//#region src/coach.ts
|
|
2221
2246
|
const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
|
|
2247
|
+
const PROGRAM_KINDS = ["calendar", "fixed"];
|
|
2248
|
+
/**
|
|
2249
|
+
* Create a standalone ongoing calendar or fixed-length program.
|
|
2250
|
+
*
|
|
2251
|
+
* TrainHeroic returns both a container id and the underlying program id. They are deliberately
|
|
2252
|
+
* named separately here because `/3.0/coach/program/{containerId}` returns 401, while the
|
|
2253
|
+
* `programId` works. This write is not idempotent: callers must not blindly retry an uncertain
|
|
2254
|
+
* result. The live API currently accepts `name` but may generate its own title; `nameApplied`
|
|
2255
|
+
* reports what happened.
|
|
2256
|
+
*/
|
|
2257
|
+
async function createProgram(client, args) {
|
|
2258
|
+
if (!PROGRAM_KINDS.includes(args.kind)) throw new Error(`Unknown program kind: ${String(args.kind)}.`);
|
|
2259
|
+
if (typeof args.name !== "string" || args.name.trim() === "") throw new Error("Program name must not be blank.");
|
|
2260
|
+
const requestedName = args.name.trim();
|
|
2261
|
+
const res = await client.request("POST", "/1.0/coach/programs/create", { body: {
|
|
2262
|
+
finite: args.kind === "fixed",
|
|
2263
|
+
name: requestedName
|
|
2264
|
+
} });
|
|
2265
|
+
if (!res.ok) {
|
|
2266
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2267
|
+
throw new Error(`Program create failed (HTTP ${res.status}): ${detail}`);
|
|
2268
|
+
}
|
|
2269
|
+
checkResponse(programCreateResponseSchema, res.data, "program create");
|
|
2270
|
+
const rec = isRecord(res.data) ? res.data : {};
|
|
2271
|
+
const nested = isRecord(rec.program) ? rec.program : {};
|
|
2272
|
+
const containerId = coerceInt(rec.id);
|
|
2273
|
+
const programId = coerceInt(rec.programId) ?? coerceInt(rec.group_program) ?? coerceInt(nested.id);
|
|
2274
|
+
if (containerId === null || programId === null) throw new Error("Program create response is missing the container id or program id.");
|
|
2275
|
+
if (typeof rec.title !== "string" || rec.title.trim() === "") throw new Error("Program create response is missing the assigned title.");
|
|
2276
|
+
const title = rec.title;
|
|
2277
|
+
return {
|
|
2278
|
+
containerId,
|
|
2279
|
+
programId,
|
|
2280
|
+
title,
|
|
2281
|
+
kind: args.kind,
|
|
2282
|
+
requestedName,
|
|
2283
|
+
nameApplied: title === requestedName
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Delete a standalone program (`DELETE /v5/programs/{programId}`).
|
|
2288
|
+
*
|
|
2289
|
+
* The live API 401s when the path id is a list_programs container id. Pass either id: this
|
|
2290
|
+
* resolves a container to its `group_program` first. Team calendars are not in that list; their
|
|
2291
|
+
* program id is deleted as given. This is not idempotent against an unknown failure.
|
|
2292
|
+
*/
|
|
2293
|
+
async function deleteProgram(client, programId) {
|
|
2294
|
+
if (!Number.isInteger(programId) || programId <= 0) throw new Error("Program id must be a positive integer.");
|
|
2295
|
+
const programs = await client.request("GET", "/1.0/coach/programs");
|
|
2296
|
+
if (!programs.ok || !Array.isArray(programs.data)) {
|
|
2297
|
+
const detail = typeof programs.data === "string" ? programs.data : JSON.stringify(programs.data);
|
|
2298
|
+
throw new Error(`GET /1.0/coach/programs failed (HTTP ${programs.status}): ${detail}`);
|
|
2299
|
+
}
|
|
2300
|
+
let targetId = programId;
|
|
2301
|
+
let containerId = null;
|
|
2302
|
+
for (const item of programs.data) {
|
|
2303
|
+
if (!isRecord(item)) continue;
|
|
2304
|
+
const groupProgram = coerceInt(item.group_program);
|
|
2305
|
+
if (coerceInt(item.id) === programId && groupProgram !== null) {
|
|
2306
|
+
containerId = programId;
|
|
2307
|
+
targetId = groupProgram;
|
|
2308
|
+
break;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
const res = await client.request("DELETE", `/v5/programs/${targetId}`, { expectedStatuses: [
|
|
2312
|
+
401,
|
|
2313
|
+
403,
|
|
2314
|
+
404
|
|
2315
|
+
] });
|
|
2316
|
+
if (!res.ok) {
|
|
2317
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2318
|
+
throw new Error(`Program delete failed (HTTP ${res.status}): ${detail}`);
|
|
2319
|
+
}
|
|
2320
|
+
return {
|
|
2321
|
+
programId: targetId,
|
|
2322
|
+
containerId
|
|
2323
|
+
};
|
|
2324
|
+
}
|
|
2222
2325
|
/** Normalize one-or-many emails into a deduped, trimmed list. */
|
|
2223
2326
|
function emailList(emails) {
|
|
2224
2327
|
return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
|
|
@@ -2316,6 +2419,52 @@ async function updateTeam(client, args) {
|
|
|
2316
2419
|
}
|
|
2317
2420
|
return res.data;
|
|
2318
2421
|
}
|
|
2422
|
+
/** Collapse the MCP/CLI XOR flags into a single publish target. */
|
|
2423
|
+
function teamPublishTarget(ids) {
|
|
2424
|
+
if (ids.programId !== void 0 && ids.teamId !== void 0) throw new Error("Pass programId or teamId, not both.");
|
|
2425
|
+
if (ids.programId !== void 0) return { programId: ids.programId };
|
|
2426
|
+
if (ids.teamId !== void 0) return { teamId: ids.teamId };
|
|
2427
|
+
throw new Error("Pass programId or teamId.");
|
|
2428
|
+
}
|
|
2429
|
+
async function programIdForTeam(client, teamId) {
|
|
2430
|
+
if (teamId <= 0) throw new Error("teamId must be positive.");
|
|
2431
|
+
const team = await client.request("GET", `/v5/teams/${teamId}`);
|
|
2432
|
+
if (!team.ok || !isRecord(team.data)) {
|
|
2433
|
+
const detail = typeof team.data === "string" ? team.data : JSON.stringify(team.data);
|
|
2434
|
+
throw new Error(`GET /v5/teams/${teamId} failed (HTTP ${team.status}): ${detail}`);
|
|
2435
|
+
}
|
|
2436
|
+
const resolved = coerceInt(team.data.group_program) ?? coerceInt(team.data.programId);
|
|
2437
|
+
if (resolved === null || resolved <= 0) throw new Error(`Team ${teamId} has no group_program.`);
|
|
2438
|
+
return resolved;
|
|
2439
|
+
}
|
|
2440
|
+
async function resolvePublishProgramId(client, target) {
|
|
2441
|
+
if ("programId" in target) return target.programId;
|
|
2442
|
+
return programIdForTeam(client, target.teamId);
|
|
2443
|
+
}
|
|
2444
|
+
/**
|
|
2445
|
+
* Update a team's auto-publish settings (`POST /1.0/coach/team/updatePublishSettings`).
|
|
2446
|
+
* The live API 500s on a partial body; it wants the full program object from
|
|
2447
|
+
* `GET /3.0/coach/program/{programId}` with `pub_*` fields merged on top.
|
|
2448
|
+
*/
|
|
2449
|
+
async function updateTeamPublishSettings(client, args) {
|
|
2450
|
+
if (Object.keys(args.patch).length === 0) throw new Error("Provide at least one pub_* field to change.");
|
|
2451
|
+
const programId = await resolvePublishProgramId(client, args);
|
|
2452
|
+
if (programId <= 0) throw new Error("programId must be positive.");
|
|
2453
|
+
const current = await client.request("GET", `/3.0/coach/program/${programId}`);
|
|
2454
|
+
if (!current.ok || !isRecord(current.data)) {
|
|
2455
|
+
const detail = typeof current.data === "string" ? current.data : JSON.stringify(current.data);
|
|
2456
|
+
throw new Error(`GET /3.0/coach/program/${programId} failed (HTTP ${current.status}): ${detail}`);
|
|
2457
|
+
}
|
|
2458
|
+
const res = await client.request("POST", "/1.0/coach/team/updatePublishSettings", { body: {
|
|
2459
|
+
...current.data,
|
|
2460
|
+
...args.patch
|
|
2461
|
+
} });
|
|
2462
|
+
if (!res.ok) {
|
|
2463
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2464
|
+
throw new Error(`updatePublishSettings failed (HTTP ${res.status}): ${detail}`);
|
|
2465
|
+
}
|
|
2466
|
+
return res.data;
|
|
2467
|
+
}
|
|
2319
2468
|
/**
|
|
2320
2469
|
* Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
|
|
2321
2470
|
* The API wants the target date as a structured object (with weekday and an isToday flag),
|
|
@@ -2567,6 +2716,23 @@ async function teamVolume(client, args) {
|
|
|
2567
2716
|
totals
|
|
2568
2717
|
};
|
|
2569
2718
|
}
|
|
2719
|
+
/** Create a reusable session template in the coach library (`POST /v5/sessions/template`). */
|
|
2720
|
+
async function createSessionTemplate(client, args) {
|
|
2721
|
+
const title = args.title.trim();
|
|
2722
|
+
if (title === "") throw new Error("Session template title must not be blank.");
|
|
2723
|
+
const res = await client.request("POST", "/v5/sessions/template", { body: definedProps({
|
|
2724
|
+
title,
|
|
2725
|
+
instruction: args.instruction
|
|
2726
|
+
}) });
|
|
2727
|
+
if (!res.ok) {
|
|
2728
|
+
const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
|
|
2729
|
+
throw new Error(`Session template create failed (HTTP ${res.status}): ${detail}`);
|
|
2730
|
+
}
|
|
2731
|
+
if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
|
|
2732
|
+
return res.data;
|
|
2733
|
+
}
|
|
2734
|
+
/** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
|
|
2735
|
+
const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
|
|
2570
2736
|
//#endregion
|
|
2571
2737
|
//#region src/main-lifts.ts
|
|
2572
2738
|
/**
|
|
@@ -2775,22 +2941,6 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
|
|
|
2775
2941
|
});
|
|
2776
2942
|
}
|
|
2777
2943
|
//#endregion
|
|
2778
|
-
//#region src/util.ts
|
|
2779
|
-
/**
|
|
2780
|
-
* Drop the keys whose value is `undefined`, so the result can be passed to a function or
|
|
2781
|
-
* spread into an object under `exactOptionalPropertyTypes` without the per-key
|
|
2782
|
-
* `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
|
|
2783
|
-
* optional ones lose `undefined` from their value type.
|
|
2784
|
-
*
|
|
2785
|
-
* Example:
|
|
2786
|
-
* definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
|
|
2787
|
-
*/
|
|
2788
|
-
function definedProps(obj) {
|
|
2789
|
-
const result = {};
|
|
2790
|
-
for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
|
|
2791
|
-
return result;
|
|
2792
|
-
}
|
|
2793
|
-
//#endregion
|
|
2794
2944
|
//#region src/messaging.ts
|
|
2795
2945
|
const BUCKETS = [
|
|
2796
2946
|
["team", "teams"],
|
|
@@ -2862,6 +3012,8 @@ var MemoryLibraryCache = class {
|
|
|
2862
3012
|
//#region src/exercise-index.ts
|
|
2863
3013
|
const LIBRARY_PATH = "/v5/exerciseLibrary/all";
|
|
2864
3014
|
const CREATE_PATH = "/2.0/coach/exercise/create";
|
|
3015
|
+
const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
|
|
3016
|
+
const DELETE_PATH = (id) => `/v5/exercises/${id}`;
|
|
2865
3017
|
const TTL_MS = 6048e5;
|
|
2866
3018
|
function toStored(ex) {
|
|
2867
3019
|
const id = coerceInt(ex.id);
|
|
@@ -2990,12 +3142,18 @@ var ExerciseLibrary = class {
|
|
|
2990
3142
|
};
|
|
2991
3143
|
}
|
|
2992
3144
|
async create(body) {
|
|
3145
|
+
return this.#writeThrough(CREATE_PATH, body, "create");
|
|
3146
|
+
}
|
|
3147
|
+
async update(id, body) {
|
|
3148
|
+
return this.#writeThrough(UPDATE_PATH(id), body, "update");
|
|
3149
|
+
}
|
|
3150
|
+
async #writeThrough(path, body, label) {
|
|
2993
3151
|
await this.ensureFresh();
|
|
2994
|
-
const res = await this.#client.request("POST",
|
|
2995
|
-
if (!res.ok) throw new Error(`Exercise
|
|
3152
|
+
const res = await this.#client.request("POST", path, { body });
|
|
3153
|
+
if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
|
|
2996
3154
|
const ex = unwrapEnvelope(res.data);
|
|
2997
3155
|
if (ex && typeof ex === "object") {
|
|
2998
|
-
checkResponse(exerciseResponseSchema, ex,
|
|
3156
|
+
checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
|
|
2999
3157
|
const s = toStored(ex);
|
|
3000
3158
|
if (s) {
|
|
3001
3159
|
this.#byId.set(s.id, s);
|
|
@@ -3004,6 +3162,15 @@ var ExerciseLibrary = class {
|
|
|
3004
3162
|
}
|
|
3005
3163
|
return ex;
|
|
3006
3164
|
}
|
|
3165
|
+
async remove(id) {
|
|
3166
|
+
const res = await this.#client.request("DELETE", DELETE_PATH(id), { expectedStatuses: [
|
|
3167
|
+
401,
|
|
3168
|
+
403,
|
|
3169
|
+
404
|
|
3170
|
+
] });
|
|
3171
|
+
if (!res.ok) throw new Error(`Exercise delete failed (HTTP ${res.status}).`);
|
|
3172
|
+
await this.recordDelete(id);
|
|
3173
|
+
}
|
|
3007
3174
|
async recordDelete(id) {
|
|
3008
3175
|
await this.ensureFresh();
|
|
3009
3176
|
if (this.#byId.delete(id)) await this.#persist();
|
|
@@ -3020,4 +3187,4 @@ var ExerciseLibrary = class {
|
|
|
3020
3187
|
}
|
|
3021
3188
|
};
|
|
3022
3189
|
//#endregion
|
|
3023
|
-
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, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
|
3190
|
+
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, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/js",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"zod": "^4.4.3",
|
|
30
|
-
"@trainheroic-unofficial/dto": "3.
|
|
30
|
+
"@trainheroic-unofficial/dto": "3.2.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^26.2.0",
|