@trainheroic-unofficial/js 1.1.0 → 1.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
@@ -1,9 +1,9 @@
1
1
  # @trainheroic-unofficial/js
2
2
 
3
- An unofficial TypeScript SDK for the TrainHeroic coaching API. It handles auth and session
4
- renewal, talks to both TrainHeroic hosts, keeps a searchable exercise library, encodes
5
- workouts into the API's payload format, and wraps messaging. It runs in any modern
6
- JavaScript runtime, including Cloudflare workerd.
3
+ An unofficial TypeScript SDK for the TrainHeroic coaching API. The client covers auth and
4
+ session renewal across both TrainHeroic hosts, a searchable exercise library, workout
5
+ encoding, and messaging. It runs in any modern JavaScript runtime, including Cloudflare
6
+ workerd.
7
7
 
8
8
  Part of the [trainheroic-unofficial](../../README.md) workspace.
9
9
 
@@ -73,7 +73,7 @@ const created = await client.request("POST", "/2.0/coach/exercise/create", {
73
73
  });
74
74
  ```
75
75
 
76
- There is no enumerated endpoint catalog; the paths are the ones the TrainHeroic web app calls.
76
+ The paths are the ones the TrainHeroic web app calls.
77
77
  Most are reachable through the typed helpers below, so you rarely call `request` directly. The
78
78
  request and response shapes those helpers use live in
79
79
  [`@trainheroic-unofficial/dto`](../dto) as zod schemas and types.
@@ -86,7 +86,7 @@ life of the process, so a fresh process logs in again. To skip that login, read
86
86
  one client and hand it to the next via the third constructor argument.
87
87
 
88
88
  After a request has run, `client.sessionId` holds the active token, typed `string | null` (it
89
- is `null` only before the first login). Persist it with your own storage — `saveToken` and
89
+ is `null` only before the first login). Persist it with your own storage; `saveToken` and
90
90
  `loadToken` below stand in for whatever you use (a file, a KV store, an env var):
91
91
 
92
92
  ```ts
@@ -130,16 +130,17 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
130
130
  client hit by concurrent requests performs a single shared login. `RequestOptions.base`
131
131
  selects the host (`coach` for `api.trainheroic.com`, `apis` for `apis.trainheroic.com`).
132
132
  - **Exercises.** `ExerciseIndex` is the interface the rest of the system codes against;
133
- `ExerciseLibrary` is the in-memory implementation that resolves names to ids, ranks
134
- fuzzy search, and persists through a `LibraryCache` (in-memory by default, JSON file via
135
- `./node`). The hosted server supplies a D1-backed implementation of the same interface.
136
- - **Workouts.** A session builder (create, save blocks and exercises, optionally publish),
137
- read-back, instruction editing, and removal, plus the encoder that turns a
138
- `WorkoutSpec` into the API's payload.
139
- - **Athlete training.** Functions for the logged-in account's own training: scheduled and
140
- completed workouts, per-exercise history, personal records, and working maxes.
141
- - **Messaging.** Listing conversation streams, reading a stream, and building, sending, or
142
- deleting a comment.
133
+ `ExerciseLibrary` is the in-memory implementation, handling name-to-id resolution,
134
+ fuzzy search ranking, and persistence through a `LibraryCache` (in-memory by default,
135
+ JSON file via `./node`). The hosted server supplies a D1-backed implementation of the
136
+ same interface.
137
+ - **Workouts.** A session builder that creates a session, saves blocks and exercises,
138
+ and optionally publishes, along with read-back, instruction editing, and removal.
139
+ Includes the encoder that turns a `WorkoutSpec` into the API's payload.
140
+ - **Athlete training.** Functions for the logged-in account's own training, covering
141
+ scheduled and completed workouts, per-exercise history, personal records, and working maxes.
142
+ - **Messaging.** Tools for conversation streams: listing them, reading a stream, and
143
+ building or sending or deleting a comment.
143
144
 
144
145
  ## Working with exercises
145
146
 
@@ -171,8 +172,8 @@ if (!match) {
171
172
 
172
173
  `buildSession` writes one session into a program on a given day: it creates the session, saves
173
174
  the blocks and exercises, and optionally publishes. `programId` identifies one of your
174
- TrainHeroic programs — find it in the program's URL in the web app, or from a programs read
175
- (`client.request("GET", ...)`). Exercise ids come from the library.
175
+ TrainHeroic programs (find it in the program's URL in the web app, or from a programs read
176
+ via `client.request("GET", ...)`). Exercise ids come from the library.
176
177
 
177
178
  ```ts
178
179
  import { buildSession, type BlockSpec } from "@trainheroic-unofficial/js";
@@ -203,13 +204,13 @@ Each exercise needs an `id`; `sets`, `reps`, `weight`, `rpe`, and a per-exercise
203
204
  optional. `reps` and `weight` take a scalar (broadcast across every set) or a per-set array
204
205
  like `reps: [5, 5, 3]`. The full field list is `ExerciseSpec` / `BlockSpec` in
205
206
  [`@trainheroic-unofficial/dto`](../dto). Loads are in whatever unit the exercise is configured
206
- for in TrainHeroic; a mismatch becomes an advisory rather than a silent change (below).
207
+ for in TrainHeroic; a mismatch becomes an advisory collected separately (see below).
207
208
 
208
- `buildSession` returns `{ pwId, workoutId }`: `pwId` is the program-workout id (the placement
209
- of the session in the program — this is the handle the other calls take), and `workoutId` is
210
- the underlying workout id. Read it back with `readSession(client, programId, date, pwId)`,
211
- publish later with `publishSession(client, pwId)`, or remove it with
212
- `removeSession(client, programId, pwId)`.
209
+ `buildSession` returns `{ pwId, workoutId }`: `pwId` is the program-workout id (the
210
+ placement of the session in the program, which is the handle subsequent calls take), and
211
+ `workoutId` is the underlying workout id. Use `pwId` with `readSession(client, programId, date, pwId)`
212
+ to read the session back. `publishSession(client, pwId)` publishes it later;
213
+ `removeSession(client, programId, pwId)` deletes it.
213
214
 
214
215
  ## Reading athlete training
215
216
 
@@ -228,13 +229,12 @@ scope.
228
229
  `buildSession` calls the encoder for you; you only deal with it directly to preview warnings.
229
230
  TrainHeroic's exercise payload expects every parameter slot present, so the encoder fills all
230
231
  of them (empty slots included) to avoid an HTTP 500. A scalar prescription is broadcast across
231
- the set count, RPE is routed into the instruction text rather than a numeric slot (the API
232
- would otherwise coerce it to load), and unit mismatches between a spec and the exercise's fixed
233
- parameter types are collected as advisories rather than silently dropped.
232
+ the set count. RPE goes into the instruction text because the API coerces a numeric slot to
233
+ load. Unit mismatches between a spec and the exercise's fixed parameter types surface as
234
+ advisories preserved in the return value of `collectAdvisories`.
234
235
 
235
- Those advisories are not part of the `buildSession` result; read them before building by
236
- calling `collectAdvisories(blocks, index)` (the `index` is an `ExerciseLibrary`), which returns
237
- the unit notes and warnings for a set of blocks.
236
+ Call `collectAdvisories(blocks, index)` before building (the `index` is an `ExerciseLibrary`)
237
+ to get the unit notes and warnings for a set of blocks.
238
238
 
239
239
  ## Develop
240
240
 
package/dist/index.d.mts CHANGED
@@ -247,20 +247,46 @@ type SetResult = {
247
247
  }>;
248
248
  };
249
249
  /**
250
- * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
251
- * snake_case keys matching the live API response shape. Each set slot (1-10) gets a
252
- * `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
253
- * `param_2_data_N` string values.
250
+ * Which write a set-write is: `"log"` records a performed result (and marks the set done),
251
+ * `"prescribe"` sets prescribed targets without marking it done. Threaded through
252
+ * {@link buildExerciseSetPayload} and the set-write helper so the two contracts share one path.
253
+ */
254
+ type SetWriteMode = "log" | "prescribe";
255
+ /**
256
+ * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
257
+ * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
258
+ * empty param slots optional; this narrows the id to a number and copies only the present per-set
259
+ * values (so the per-set type stays free of `undefined` under exactOptionalPropertyTypes). Shared
260
+ * by the MCP tools and the CLI so the mapping lives in one place rather than once per surface.
261
+ */
262
+ declare function toSetResults(results: ReadonlyArray<{
263
+ savedWorkoutSetExerciseId: number | string;
264
+ sets: ReadonlyArray<{
265
+ param1?: number | string | undefined;
266
+ param2?: number | string | undefined;
267
+ }>;
268
+ }>): SetResult[];
269
+ /**
270
+ * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
271
+ * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
272
+ * `param_2_data_N` string values plus a `param_N_made` flag.
273
+ *
274
+ * `mode` selects which write this is — the same endpoint serves both:
275
+ * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
276
+ * and the exercise `completed` flag is 1 when any set has data.
277
+ * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
278
+ * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
279
+ * coach edits an athlete's prescribed reps/weight.
254
280
  *
255
281
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
256
282
  * required from the live exercise record; everything else is derived from `results`.
257
283
  *
258
- * Exported for unit testing — callers should use `logAthleteSet` instead.
284
+ * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
259
285
  */
260
- declare function buildExerciseLogPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly {
286
+ declare function buildExerciseSetPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly {
261
287
  param1?: number | string;
262
288
  param2?: number | string;
263
- }[]): Record<string, unknown>;
289
+ }[], mode: SetWriteMode): Record<string, unknown>;
264
290
  /**
265
291
  * Locate the target saved workout set across all program workouts on the given day.
266
292
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -332,6 +358,61 @@ declare function logForAthlete(client: TrainHeroicClient, args: {
332
358
  savedWorkoutSetId: number;
333
359
  exercisesLogged: number;
334
360
  }>;
361
+ /**
362
+ * Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
363
+ * workout sets WITHOUT marking it performed — the API equivalent of the app's editing an athlete's
364
+ * prescribed values. Writes each exercise's per-set targets via
365
+ * `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` with `param_N_made = 0` /
366
+ * `completed = 0`, and (unlike {@link logForAthlete}) skips the set-completion step, so the set
367
+ * stays open for the athlete to log against.
368
+ *
369
+ * Overrides only this athlete's copy of the set; the team/program prescription is untouched, so
370
+ * other athletes on the same program keep the original targets. The write REPLACES the slot's
371
+ * prescribed values, so pass the full per-set prescription you want — `param1` is reps, `param2`
372
+ * is weight, and an omitted param is written empty (clearing it), not left as-is.
373
+ *
374
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only and return 401/403; real (invited)
375
+ * athletes accept it.
376
+ */
377
+ declare function prescribeForAthlete(client: TrainHeroicClient, args: {
378
+ athleteId: number;
379
+ date: string;
380
+ savedWorkoutSetId: number;
381
+ results: readonly SetResult[];
382
+ }): Promise<{
383
+ savedWorkoutSetId: number;
384
+ exercisesPrescribed: number;
385
+ }>;
386
+ /** Outcome of a per-athlete exercise swap: the slot that changed and what it changed to/from. */
387
+ type SwapExerciseResult = {
388
+ savedWorkoutSetExerciseId: number; /** The athlete who owns the slot (`user_id` off the updated row), when the API returns it. */
389
+ athleteId: number | null; /** The exercise now scheduled in the slot. */
390
+ newExerciseId: number;
391
+ newExerciseTitle: string | null; /** The team/program's original prescription, left untouched (`workout_set_exercise.exercise_id`). */
392
+ originalTeamExerciseId: number | null;
393
+ };
394
+ /**
395
+ * Swap the exercise prescribed in one of an athlete's saved-workout slots for a different
396
+ * exercise — the API equivalent of the app's per-athlete "swap exercise":
397
+ * `PUT /v5/savedWorkoutSetExercises/{savedWorkoutSetExerciseId}?exerciseId={exerciseId}` with an
398
+ * empty body. The new exercise rides in the query string, not the body.
399
+ *
400
+ * This overrides only this athlete's copy of the slot; the underlying team/program prescription
401
+ * (`workout_set_exercise.exercise_id`) is untouched, so other athletes on the same program keep
402
+ * the original exercise. A coach's session token may write another user's row because the row
403
+ * already carries its owner's `user_id`.
404
+ *
405
+ * `savedWorkoutSetExerciseId` is the same id {@link logForAthlete}/{@link logAthleteSet} use,
406
+ * read off the athlete's saved workouts (the raw view). `exerciseId` is any exercise id the org
407
+ * can use (resolve one via the exercise index).
408
+ *
409
+ * NOTE: as with logging, TrainHeroic's seeded *demo* athletes are read-only and return 401/403;
410
+ * real (invited) athletes accept the swap.
411
+ */
412
+ declare function swapAthleteExercise(client: TrainHeroicClient, args: {
413
+ savedWorkoutSetExerciseId: number;
414
+ exerciseId: number;
415
+ }): Promise<SwapExerciseResult>;
335
416
  type PersonalWorkoutCreated = {
336
417
  programWorkoutId: number;
337
418
  workoutId: number;
@@ -582,4 +663,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
582
663
  stats(): Promise<Record<string, unknown>>;
583
664
  }
584
665
  //#endregion
585
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SessionExercise, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, teamVolume, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
666
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/dist/index.mjs CHANGED
@@ -722,29 +722,59 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
722
722
  }
723
723
  const MAX_PARAM_SLOTS = 10;
724
724
  /**
725
- * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
726
- * snake_case keys matching the live API response shape. Each set slot (1-10) gets a
727
- * `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
728
- * `param_2_data_N` string values.
725
+ * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
726
+ * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
727
+ * empty param slots optional; this narrows the id to a number and copies only the present per-set
728
+ * values (so the per-set type stays free of `undefined` under exactOptionalPropertyTypes). Shared
729
+ * by the MCP tools and the CLI so the mapping lives in one place rather than once per surface.
730
+ */
731
+ function toSetResults(results) {
732
+ return results.map((r) => {
733
+ const id = coerceInt(r.savedWorkoutSetExerciseId);
734
+ if (id === null) throw new Error(`Invalid savedWorkoutSetExerciseId: ${String(r.savedWorkoutSetExerciseId)}`);
735
+ return {
736
+ savedWorkoutSetExerciseId: id,
737
+ sets: r.sets.map((s) => {
738
+ const slot = {};
739
+ if (s.param1 !== void 0) slot.param1 = s.param1;
740
+ if (s.param2 !== void 0) slot.param2 = s.param2;
741
+ return slot;
742
+ })
743
+ };
744
+ });
745
+ }
746
+ /**
747
+ * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
748
+ * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
749
+ * `param_2_data_N` string values plus a `param_N_made` flag.
750
+ *
751
+ * `mode` selects which write this is — the same endpoint serves both:
752
+ * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
753
+ * and the exercise `completed` flag is 1 when any set has data.
754
+ * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
755
+ * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
756
+ * coach edits an athlete's prescribed reps/weight.
729
757
  *
730
758
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
731
759
  * required from the live exercise record; everything else is derived from `results`.
732
760
  *
733
- * Exported for unit testing — callers should use `logAthleteSet` instead.
761
+ * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
734
762
  */
735
- function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
763
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
736
764
  if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
765
+ const performed = mode === "log";
766
+ const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
737
767
  const body = {
738
768
  id: savedWorkoutSetExerciseId,
739
769
  saved_workout_set_id: savedWorkoutSetId,
740
770
  workout_set_exercise_id: workoutSetExerciseId,
741
- completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
771
+ completed: performed && hasData ? 1 : 0
742
772
  };
743
773
  for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
744
774
  const slot = results[i - 1];
745
775
  const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
746
776
  const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
747
- body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
777
+ body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
748
778
  body[`param_1_data_${i}`] = p1;
749
779
  body[`param_2_data_${i}`] = p2;
750
780
  }
@@ -845,7 +875,11 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
845
875
  * by the respective PUT bodies.
846
876
  */
847
877
  async function logAthleteSet(client, args) {
848
- return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
878
+ const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
879
+ return {
880
+ savedWorkoutSetId: r.savedWorkoutSetId,
881
+ exercisesLogged: r.exercisesWritten
882
+ };
849
883
  }
850
884
  /**
851
885
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
@@ -859,24 +893,94 @@ async function logAthleteSet(client, args) {
859
893
  */
860
894
  async function logForAthlete(client, args) {
861
895
  const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
862
- return writeSetResults(client, {
896
+ const r = await writeSetResults(client, {
863
897
  role: "coach",
864
898
  athleteId: args.athleteId
865
- }, workouts, args.savedWorkoutSetId, args.results);
899
+ }, workouts, args.savedWorkoutSetId, args.results, "log");
900
+ return {
901
+ savedWorkoutSetId: r.savedWorkoutSetId,
902
+ exercisesLogged: r.exercisesWritten
903
+ };
866
904
  }
867
905
  /**
868
- * Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
869
- * `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
870
- * `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
871
- * exercise's entered data to its own endpoint (the only path that actually stores reps and
872
- * weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
873
- * shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
906
+ * Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
907
+ * workout sets WITHOUT marking it performed — the API equivalent of the app's editing an athlete's
908
+ * prescribed values. Writes each exercise's per-set targets via
909
+ * `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` with `param_N_made = 0` /
910
+ * `completed = 0`, and (unlike {@link logForAthlete}) skips the set-completion step, so the set
911
+ * stays open for the athlete to log against.
912
+ *
913
+ * Overrides only this athlete's copy of the set; the team/program prescription is untouched, so
914
+ * other athletes on the same program keep the original targets. The write REPLACES the slot's
915
+ * prescribed values, so pass the full per-set prescription you want — `param1` is reps, `param2`
916
+ * is weight, and an omitted param is written empty (clearing it), not left as-is.
917
+ *
918
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only and return 401/403; real (invited)
919
+ * athletes accept it.
874
920
  */
875
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
921
+ async function prescribeForAthlete(client, args) {
922
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
923
+ const r = await writeSetResults(client, {
924
+ role: "coach",
925
+ athleteId: args.athleteId
926
+ }, workouts, args.savedWorkoutSetId, args.results, "prescribe");
927
+ return {
928
+ savedWorkoutSetId: r.savedWorkoutSetId,
929
+ exercisesPrescribed: r.exercisesWritten
930
+ };
931
+ }
932
+ /**
933
+ * Swap the exercise prescribed in one of an athlete's saved-workout slots for a different
934
+ * exercise — the API equivalent of the app's per-athlete "swap exercise":
935
+ * `PUT /v5/savedWorkoutSetExercises/{savedWorkoutSetExerciseId}?exerciseId={exerciseId}` with an
936
+ * empty body. The new exercise rides in the query string, not the body.
937
+ *
938
+ * This overrides only this athlete's copy of the slot; the underlying team/program prescription
939
+ * (`workout_set_exercise.exercise_id`) is untouched, so other athletes on the same program keep
940
+ * the original exercise. A coach's session token may write another user's row because the row
941
+ * already carries its owner's `user_id`.
942
+ *
943
+ * `savedWorkoutSetExerciseId` is the same id {@link logForAthlete}/{@link logAthleteSet} use,
944
+ * read off the athlete's saved workouts (the raw view). `exerciseId` is any exercise id the org
945
+ * can use (resolve one via the exercise index).
946
+ *
947
+ * NOTE: as with logging, TrainHeroic's seeded *demo* athletes are read-only and return 401/403;
948
+ * real (invited) athletes accept the swap.
949
+ */
950
+ async function swapAthleteExercise(client, args) {
951
+ const res = await client.request("PUT", `/v5/savedWorkoutSetExercises/${args.savedWorkoutSetExerciseId}?exerciseId=${args.exerciseId}`);
952
+ if (!res.ok) {
953
+ const readOnly = res.status === 401 || res.status === 403 ? ` Athlete may be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; swaps only persist for real (invited) athletes.` : "";
954
+ throw new Error(`Swap failed (HTTP ${res.status}) for savedWorkoutSetExercise ${args.savedWorkoutSetExerciseId}.${readOnly}`);
955
+ }
956
+ const row = isRecord(res.data) ? res.data : {};
957
+ const template = isRecord(row.workout_set_exercise) ? row.workout_set_exercise : {};
958
+ const exercise = isRecord(row.exercise) ? row.exercise : {};
959
+ return {
960
+ savedWorkoutSetExerciseId: args.savedWorkoutSetExerciseId,
961
+ athleteId: coerceInt(row.user_id),
962
+ newExerciseId: coerceInt(row.exercise_id) ?? args.exerciseId,
963
+ newExerciseTitle: str$1(exercise.title),
964
+ originalTeamExerciseId: coerceInt(template.exercise_id)
965
+ };
966
+ }
967
+ /**
968
+ * Shared set-write behind {@link logAthleteSet}, {@link logForAthlete}, and
969
+ * {@link prescribeForAthlete}. `target` selects the surface: `athlete` writes `/1.0/athlete/...`;
970
+ * `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body.
971
+ *
972
+ * Step 1 PUTs each exercise's per-set values to its own endpoint (the only path that actually
973
+ * stores reps and weight). `mode` decides what those values mean: `"log"` records them as a
974
+ * performed result and runs Step 2, which marks the set completed (that body needs the app's
975
+ * camelCase in-memory shape and the full list of savedWorkoutSetExercise IDs in the set, not only
976
+ * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
977
+ * open.
978
+ */
979
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
876
980
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
877
981
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
878
982
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
879
- let exercisesLogged = 0;
983
+ let exercisesWritten = 0;
880
984
  for (const result of results) {
881
985
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
882
986
  if (!ex) {
@@ -890,25 +994,27 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
890
994
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
891
995
  if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
892
996
  const body = {
893
- ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
997
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
894
998
  ...extra
895
999
  };
896
1000
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
897
1001
  if (!res.ok) {
898
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for results — TrainHeroic's seeded demo/sample athletes return ${res.status} here; results only persist for real (invited) athletes.` : "";
899
- throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1002
+ const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
1003
+ throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
900
1004
  }
901
- exercisesLogged += 1;
1005
+ exercisesWritten += 1;
1006
+ }
1007
+ if (mode === "log") {
1008
+ const setBody = {
1009
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1010
+ ...extra
1011
+ };
1012
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1013
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
902
1014
  }
903
- const setBody = {
904
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
905
- ...extra
906
- };
907
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
908
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
909
1015
  return {
910
1016
  savedWorkoutSetId,
911
- exercisesLogged
1017
+ exercisesWritten
912
1018
  };
913
1019
  }
914
1020
  /**
@@ -2031,4 +2137,4 @@ var ExerciseLibrary = class {
2031
2137
  }
2032
2138
  };
2033
2139
  //#endregion
2034
- export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, teamVolume, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
2140
+ export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "1.1.0",
3
+ "version": "1.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": "1.1.0"
30
+ "@trainheroic-unofficial/dto": "1.2.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",