@trainheroic-unofficial/js 3.1.1 → 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 CHANGED
@@ -165,14 +165,18 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
165
165
  returns both `containerId` (the id in `GET /1.0/coach/programs`) and `programId` (the id used by
166
166
  program detail and workout writes). TrainHeroic may replace the requested name; inspect the
167
167
  returned `title` and `nameApplied`. Creation is not idempotent, so do not blindly retry an
168
- uncertain result.
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).
169
170
 
170
171
  ## Working with exercises
171
172
 
172
173
  `ExerciseLibrary` loads the full library once, caches it, and answers name lookups and fuzzy
173
174
  search against the in-memory copy. By default it caches in memory; pass a `JsonFileLibraryCache`
174
175
  from `./node` to persist between runs (it writes to `defaultCachePath()`,
175
- `~/.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.
176
180
 
177
181
  ```ts
178
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
@@ -178,6 +178,10 @@ interface ExerciseIndex {
178
178
  get(id: number): Promise<Record<string, unknown> | null>;
179
179
  defaultsMany(ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
180
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>;
181
185
  recordDelete(id: number): Promise<void>;
182
186
  stats(): Promise<Record<string, unknown>>;
183
187
  }
@@ -209,6 +213,9 @@ declare function fetchRosterActivity(client: TrainHeroicClient, athleteIds: read
209
213
  declare function fetchAthletePrefs(client: TrainHeroicClient): Promise<AthletePrefs>;
210
214
  declare function fetchWorkingMaxes(client: TrainHeroicClient): Promise<AthleteWorkingMax[]>;
211
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[]>;
212
219
  /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
213
220
  declare function searchExerciseHistory(client: TrainHeroicClient, query: string, limit?: number): Promise<ExerciseHistoryListItem[]>;
214
221
  declare function fetchExerciseHistoryDetail(client: TrainHeroicClient, exerciseId: number, userId: number): Promise<ExerciseHistoryDetail>;
@@ -809,6 +816,20 @@ declare function createProgram(client: TrainHeroicClient, args: {
809
816
  kind: ProgramKind;
810
817
  name: string;
811
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>;
812
833
  /** A roster member as id + display name. */
813
834
  type CoachRosterAthlete = {
814
835
  id: number;
@@ -848,6 +869,24 @@ declare function updateTeam(client: TrainHeroicClient, args: {
848
869
  title?: string;
849
870
  groupProgram?: number;
850
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>;
851
890
  /**
852
891
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
853
892
  * The API wants the target date as a structured object (with weekday and an isToday flag),
@@ -910,6 +949,10 @@ declare function teamVolume(client: TrainHeroicClient, args: {
910
949
  dateStart: string;
911
950
  dateEnd: string;
912
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";
913
956
  //#endregion
914
957
  //#region src/util.d.ts
915
958
  /**
@@ -1021,8 +1064,10 @@ declare class ExerciseLibrary implements ExerciseIndex {
1021
1064
  search(query: string, limit?: number): Promise<ExerciseView[]>;
1022
1065
  resolve(name: string): Promise<ResolveResult>;
1023
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>;
1024
1069
  recordDelete(id: number): Promise<void>;
1025
1070
  stats(): Promise<Record<string, unknown>>;
1026
1071
  }
1027
1072
  //#endregion
1028
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, 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, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, 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, createProgram, 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
@@ -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,
@@ -2258,6 +2283,45 @@ async function createProgram(client, args) {
2258
2283
  nameApplied: title === requestedName
2259
2284
  };
2260
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
+ }
2261
2325
  /** Normalize one-or-many emails into a deduped, trimmed list. */
2262
2326
  function emailList(emails) {
2263
2327
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
@@ -2355,6 +2419,52 @@ async function updateTeam(client, args) {
2355
2419
  }
2356
2420
  return res.data;
2357
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
+ }
2358
2468
  /**
2359
2469
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2360
2470
  * The API wants the target date as a structured object (with weekday and an isToday flag),
@@ -2606,6 +2716,23 @@ async function teamVolume(client, args) {
2606
2716
  totals
2607
2717
  };
2608
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";
2609
2736
  //#endregion
2610
2737
  //#region src/main-lifts.ts
2611
2738
  /**
@@ -2814,22 +2941,6 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
2814
2941
  });
2815
2942
  }
2816
2943
  //#endregion
2817
- //#region src/util.ts
2818
- /**
2819
- * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2820
- * spread into an object under `exactOptionalPropertyTypes` without the per-key
2821
- * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2822
- * optional ones lose `undefined` from their value type.
2823
- *
2824
- * Example:
2825
- * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2826
- */
2827
- function definedProps(obj) {
2828
- const result = {};
2829
- for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2830
- return result;
2831
- }
2832
- //#endregion
2833
2944
  //#region src/messaging.ts
2834
2945
  const BUCKETS = [
2835
2946
  ["team", "teams"],
@@ -2901,6 +3012,8 @@ var MemoryLibraryCache = class {
2901
3012
  //#region src/exercise-index.ts
2902
3013
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
2903
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}`;
2904
3017
  const TTL_MS = 6048e5;
2905
3018
  function toStored(ex) {
2906
3019
  const id = coerceInt(ex.id);
@@ -3029,12 +3142,18 @@ var ExerciseLibrary = class {
3029
3142
  };
3030
3143
  }
3031
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) {
3032
3151
  await this.ensureFresh();
3033
- const res = await this.#client.request("POST", CREATE_PATH, { body });
3034
- if (!res.ok) throw new Error(`Exercise create failed (HTTP ${res.status}).`);
3152
+ const res = await this.#client.request("POST", path, { body });
3153
+ if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
3035
3154
  const ex = unwrapEnvelope(res.data);
3036
3155
  if (ex && typeof ex === "object") {
3037
- checkResponse(exerciseResponseSchema, ex, "exercise create");
3156
+ checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
3038
3157
  const s = toStored(ex);
3039
3158
  if (s) {
3040
3159
  this.#byId.set(s.id, s);
@@ -3043,6 +3162,15 @@ var ExerciseLibrary = class {
3043
3162
  }
3044
3163
  return ex;
3045
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
+ }
3046
3174
  async recordDelete(id) {
3047
3175
  await this.ensureFresh();
3048
3176
  if (this.#byId.delete(id)) await this.#persist();
@@ -3059,4 +3187,4 @@ var ExerciseLibrary = class {
3059
3187
  }
3060
3188
  };
3061
3189
  //#endregion
3062
- 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, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, 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.1.1",
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.1.1"
30
+ "@trainheroic-unofficial/dto": "3.2.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.2.0",