@trainheroic-unofficial/js 0.6.4 → 1.0.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/dist/index.d.mts CHANGED
@@ -158,6 +158,13 @@ declare function fetchPersonalRecords(client: TrainHeroicClient, exerciseId: num
158
158
  declare function fetchExerciseStats(client: TrainHeroicClient, exerciseId: number, userId: number, date: string): Promise<ExerciseStats>;
159
159
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
160
160
  declare function fetchAthleteWorkouts(client: TrainHeroicClient, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
161
+ /**
162
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
163
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
164
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
165
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
166
+ */
167
+ declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
161
168
  /**
162
169
  * A coach's month view of a roster athlete's logged sessions
163
170
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
@@ -179,6 +186,29 @@ declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number,
179
186
  */
180
187
  declare function presentAthleteWorkout(raw: ProgramWorkout): AthleteWorkoutView;
181
188
  declare function presentAthleteWorkouts(list: readonly ProgramWorkout[]): AthleteWorkoutView[];
189
+ /** The minimal id scaffold `log-set` / `logForAthlete` needs for one saved workout set. */
190
+ type LogSetTarget = {
191
+ date: string;
192
+ workoutTitle: string; /** The id for `--set` (logAthleteSet/logForAthlete `savedWorkoutSetId`). */
193
+ savedWorkoutSetId: number;
194
+ setTitle: string | null;
195
+ exercises: Array<{
196
+ /** The id for each result's `savedWorkoutSetExerciseId`. */savedWorkoutSetExerciseId: number;
197
+ title: string;
198
+ units: ReturnType<typeof exerciseUnits>;
199
+ prescribed: string[];
200
+ performed: string[];
201
+ }>;
202
+ };
203
+ /**
204
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
205
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
206
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
207
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
208
+ * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
209
+ * with no resolvable id.
210
+ */
211
+ declare function presentLogTargets(list: readonly ProgramWorkout[]): LogSetTarget[];
182
212
  /**
183
213
  * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
184
214
  * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
@@ -283,6 +313,25 @@ declare function logAthleteSet(client: TrainHeroicClient, args: {
283
313
  savedWorkoutSetId: number;
284
314
  exercisesLogged: number;
285
315
  }>;
316
+ /**
317
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
318
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
319
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
320
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
321
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
322
+ *
323
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
324
+ * data-write step; real (invited) athletes accept it.
325
+ */
326
+ declare function logForAthlete(client: TrainHeroicClient, args: {
327
+ athleteId: number;
328
+ date: string;
329
+ savedWorkoutSetId: number;
330
+ results: readonly SetResult[];
331
+ }): Promise<{
332
+ savedWorkoutSetId: number;
333
+ exercisesLogged: number;
334
+ }>;
286
335
  type PersonalWorkoutCreated = {
287
336
  programWorkoutId: number;
288
337
  workoutId: number;
@@ -311,6 +360,77 @@ declare function addExercisesToWorkout(client: TrainHeroicClient, workoutId: num
311
360
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
312
361
  declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
313
362
  //#endregion
363
+ //#region src/coach.d.ts
364
+ declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
365
+ /**
366
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
367
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
368
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
369
+ */
370
+ declare function inviteAthletes(client: TrainHeroicClient, args: {
371
+ teamId: number;
372
+ emails: readonly string[];
373
+ message?: string;
374
+ }): Promise<{
375
+ teamId: number;
376
+ invited: string[];
377
+ result: unknown;
378
+ }>;
379
+ /**
380
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
381
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
382
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
383
+ */
384
+ declare function copySession(client: TrainHeroicClient, args: {
385
+ toProgramId: number;
386
+ pwId: number;
387
+ toDate: string;
388
+ }): Promise<unknown>;
389
+ declare const ANALYTICS_METRIC_KEYS: readonly ["readiness-team", "readiness-athlete", "lift-1rm-history", "training-summary-athlete", "compliance-team", "lift-progress-team", "working-max-history"];
390
+ type AnalyticsMetric = (typeof ANALYTICS_METRIC_KEYS)[number];
391
+ /**
392
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
393
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
394
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
395
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
396
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
397
+ */
398
+ declare function analyticsMetricCatalog(): Array<{
399
+ metric: AnalyticsMetric;
400
+ scope: "team" | "user";
401
+ scopeParam: "teamId" | "userIds";
402
+ requires: string[];
403
+ optional: string[];
404
+ }>;
405
+ type AnalyticsQueryArgs = {
406
+ metric: AnalyticsMetric;
407
+ teamId?: number;
408
+ userIds?: readonly number[];
409
+ exerciseId?: number;
410
+ date?: string;
411
+ dateStart?: string;
412
+ dateEnd?: string;
413
+ useMetric?: boolean;
414
+ };
415
+ /**
416
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
417
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
418
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
419
+ */
420
+ declare function queryAnalytics(client: TrainHeroicClient, args: AnalyticsQueryArgs): Promise<unknown>;
421
+ //#endregion
422
+ //#region src/util.d.ts
423
+ /**
424
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
425
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
426
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
427
+ * optional ones lose `undefined` from their value type.
428
+ *
429
+ * Example:
430
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
431
+ */
432
+ declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclude<T[K], undefined> };
433
+ //#endregion
314
434
  //#region src/workout-encode.d.ts
315
435
  declare const LEADERBOARD_TYPE: Readonly<Record<string, number>>;
316
436
  declare const LEADERBOARD_LABEL: Readonly<Record<number, string>>;
@@ -400,4 +520,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
400
520
  stats(): Promise<Record<string, unknown>>;
401
521
  }
402
522
  //#endregion
403
- export { AddedExercise, ApiBase, BuildOptions, ClientResult, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, SetResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
523
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, BuildOptions, ClientResult, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSetTarget, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, 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, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { exerciseLibraryResponseSchema, exerciseResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
1
+ import { exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  export * from "@trainheroic-unofficial/dto";
3
3
  //#region src/auth.ts
4
4
  const AUTH_URL = "https://apis.trainheroic.com/auth";
@@ -405,6 +405,15 @@ function fetchAthleteWorkouts(client, startDate, endDate) {
405
405
  return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
406
406
  }
407
407
  /**
408
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
409
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
410
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
411
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
412
+ */
413
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
414
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
415
+ }
416
+ /**
408
417
  * A coach's month view of a roster athlete's logged sessions
409
418
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
410
419
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
@@ -587,6 +596,50 @@ function presentAthleteWorkouts(list) {
587
596
  return list.map(presentAthleteWorkout);
588
597
  }
589
598
  /**
599
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
600
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
601
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
602
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
603
+ * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
604
+ * with no resolvable id.
605
+ */
606
+ function presentLogTargets(list) {
607
+ const targets = [];
608
+ for (const pw of list) {
609
+ const rec = pw;
610
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
611
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
612
+ if (!saved) continue;
613
+ const date = str$1(rec.date) ?? "";
614
+ const workoutTitle = str$1(rec.workout_title) ?? "";
615
+ const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
616
+ for (const s of sets) {
617
+ if (!isRecord(s)) continue;
618
+ const savedWorkoutSetId = coerceInt(s.id);
619
+ if (savedWorkoutSetId === null) continue;
620
+ const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
621
+ const id = coerceInt(ex.id);
622
+ if (id === null) return null;
623
+ return {
624
+ savedWorkoutSetExerciseId: id,
625
+ title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
626
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
627
+ prescribed: prescribedSets(ex),
628
+ performed: performedSets(ex)
629
+ };
630
+ }).filter((e) => e !== null);
631
+ targets.push({
632
+ date,
633
+ workoutTitle,
634
+ savedWorkoutSetId,
635
+ setTitle: str$1(s.title),
636
+ exercises
637
+ });
638
+ }
639
+ }
640
+ return targets;
641
+ }
642
+ /**
590
643
  * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
591
644
  * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
592
645
  * completion flag). `limit` keeps the most recent N by date (newest first). Both are pure
@@ -704,6 +757,7 @@ function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
704
757
  * record so callers can build the set-completion PUT body via `buildSetCompletePayload`.
705
758
  */
706
759
  function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
760
+ const available = [];
707
761
  for (const pw of workouts) {
708
762
  const rec = pw;
709
763
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
@@ -712,18 +766,29 @@ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
712
766
  const sets = Array.isArray(sw.workoutSets) ? sw.workoutSets : [];
713
767
  for (const s of sets) {
714
768
  if (!isRecord(s)) continue;
769
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [];
715
770
  if (coerceInt(s.id) === savedWorkoutSetId) {
716
771
  const savedWorkoutId = coerceInt(sw.id);
717
772
  if (!savedWorkoutId) continue;
718
773
  return {
719
774
  savedWorkoutId,
720
- exercises: Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [],
775
+ exercises,
721
776
  rawSet: s
722
777
  };
723
778
  }
779
+ const setId = coerceInt(s.id);
780
+ if (setId !== null) {
781
+ const exLabels = exercises.map((ex) => {
782
+ const exId = coerceInt(ex.id);
783
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
784
+ return exId === null ? null : `${exId} (${title})`;
785
+ }).filter((x) => x !== null);
786
+ available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
787
+ }
724
788
  }
725
789
  }
726
- throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.`);
790
+ const hint = available.length > 0 ? ` Saved workout sets present on this date: ${available.join("; ")}. Pass a "set N" id to --set (the savedWorkoutSetId), and the matching "exercise id" as savedWorkoutSetExerciseId in the results.` : " No saved workout is scheduled on this date — log against a date that has a workout (find it via athlete-workouts / coach athlete-workouts).";
791
+ throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.${hint}`);
727
792
  }
728
793
  /**
729
794
  * Build the body for `PUT /1.0/athlete/savedworkoutset/{id}` that marks the set completed.
@@ -780,23 +845,69 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
780
845
  * by the respective PUT bodies.
781
846
  */
782
847
  async function logAthleteSet(client, args) {
783
- const { exercises, rawSet } = findSavedWorkoutSet(await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId);
848
+ return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
849
+ }
850
+ /**
851
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
852
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
853
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
854
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
855
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
856
+ *
857
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
858
+ * data-write step; real (invited) athletes accept it.
859
+ */
860
+ async function logForAthlete(client, args) {
861
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
862
+ return writeSetResults(client, {
863
+ role: "coach",
864
+ athleteId: args.athleteId
865
+ }, workouts, args.savedWorkoutSetId, args.results);
866
+ }
867
+ /**
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).
874
+ */
875
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
876
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
877
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
878
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
784
879
  let exercisesLogged = 0;
785
- for (const result of args.results) {
880
+ for (const result of results) {
786
881
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
787
- if (!ex) throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${args.savedWorkoutSetId}.`);
882
+ if (!ex) {
883
+ const valid = exercises.map((e) => {
884
+ const id = coerceInt(e.id);
885
+ const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
886
+ return id === null ? null : `${id} (${title})`;
887
+ }).filter((x) => x !== null);
888
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
889
+ }
788
890
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
789
891
  if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
790
- const body = buildExerciseLogPayload(result.savedWorkoutSetExerciseId, args.savedWorkoutSetId, workoutSetExerciseId, result.sets);
791
- const res = await client.request("PUT", `/1.0/athlete/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}`, { body });
792
- if (!res.ok) throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).`);
892
+ const body = {
893
+ ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
894
+ ...extra
895
+ };
896
+ const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
897
+ 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}`);
900
+ }
793
901
  exercisesLogged += 1;
794
902
  }
795
- const setBody = buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true);
796
- const setRes = await client.request("PUT", `/1.0/athlete/savedworkoutset/${args.savedWorkoutSetId}`, { body: setBody });
797
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${args.savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
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}).`);
798
909
  return {
799
- savedWorkoutSetId: args.savedWorkoutSetId,
910
+ savedWorkoutSetId,
800
911
  exercisesLogged
801
912
  };
802
913
  }
@@ -860,6 +971,219 @@ function presentExerciseHistory(detail) {
860
971
  };
861
972
  }
862
973
  //#endregion
974
+ //#region src/coach.ts
975
+ const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
976
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
977
+ function emailList(emails) {
978
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
979
+ }
980
+ /**
981
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
982
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
983
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
984
+ */
985
+ async function inviteAthletes(client, args) {
986
+ const list = emailList(args.emails);
987
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
988
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
989
+ if (!validation.ok) {
990
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
991
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
992
+ }
993
+ const valid = Array.isArray(validation.data) ? validation.data : list;
994
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
995
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
996
+ teamType: 0,
997
+ teamId: args.teamId,
998
+ orgId: null,
999
+ emails: valid,
1000
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1001
+ } });
1002
+ if (!invite.ok) {
1003
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1004
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1005
+ }
1006
+ return {
1007
+ teamId: args.teamId,
1008
+ invited: valid,
1009
+ result: invite.data
1010
+ };
1011
+ }
1012
+ /**
1013
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1014
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
1015
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
1016
+ */
1017
+ async function copySession(client, args) {
1018
+ const [year, month, day] = parseWorkoutDate(args.toDate);
1019
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1020
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1021
+ const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1022
+ toProgramId: args.toProgramId,
1023
+ pwId: args.pwId,
1024
+ toDate: {
1025
+ date: iso,
1026
+ day,
1027
+ month,
1028
+ year,
1029
+ dayOfWeek,
1030
+ isToday: false
1031
+ }
1032
+ } });
1033
+ if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
1034
+ return res.data;
1035
+ }
1036
+ const ANALYTICS_METRIC_KEYS = [
1037
+ "readiness-team",
1038
+ "readiness-athlete",
1039
+ "lift-1rm-history",
1040
+ "training-summary-athlete",
1041
+ "compliance-team",
1042
+ "lift-progress-team",
1043
+ "working-max-history"
1044
+ ];
1045
+ const ANALYTICS_METRICS = {
1046
+ "readiness-team": {
1047
+ path: "/v5/analytics/readiness/teams",
1048
+ scope: "team",
1049
+ inputs: ["date"],
1050
+ requires: ["date"]
1051
+ },
1052
+ "readiness-athlete": {
1053
+ path: "/v5/analytics/readiness/users",
1054
+ scope: "user",
1055
+ inputs: ["dateStart", "dateEnd"],
1056
+ requires: ["dateStart", "dateEnd"]
1057
+ },
1058
+ "lift-1rm-history": {
1059
+ path: "/v5/analytics/lift-one-rep-max-history/users",
1060
+ scope: "user",
1061
+ inputs: [
1062
+ "dateStart",
1063
+ "dateEnd",
1064
+ "exerciseId",
1065
+ "useMetric"
1066
+ ],
1067
+ requires: [
1068
+ "dateStart",
1069
+ "dateEnd",
1070
+ "exerciseId"
1071
+ ]
1072
+ },
1073
+ "training-summary-athlete": {
1074
+ path: "/v5/analytics/training-summary/users",
1075
+ scope: "user",
1076
+ inputs: ["dateStart", "dateEnd"],
1077
+ requires: ["dateStart", "dateEnd"]
1078
+ },
1079
+ "compliance-team": {
1080
+ path: "/v5/analytics/compliance",
1081
+ scope: "team",
1082
+ inputs: ["dateStart", "dateEnd"],
1083
+ requires: ["dateStart", "dateEnd"]
1084
+ },
1085
+ "lift-progress-team": {
1086
+ path: "/v5/analytics/lift-progress/teams",
1087
+ scope: "team",
1088
+ inputs: [
1089
+ "exerciseId",
1090
+ "dateStart",
1091
+ "dateEnd"
1092
+ ],
1093
+ requires: [
1094
+ "exerciseId",
1095
+ "dateStart",
1096
+ "dateEnd"
1097
+ ]
1098
+ },
1099
+ "working-max-history": {
1100
+ path: "/v5/analytics/working-max-history/users",
1101
+ scope: "user",
1102
+ inputs: [
1103
+ "exerciseId",
1104
+ "dateStart",
1105
+ "dateEnd",
1106
+ "useMetric"
1107
+ ],
1108
+ requires: ["exerciseId"]
1109
+ }
1110
+ };
1111
+ /**
1112
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
1113
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
1114
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
1115
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
1116
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
1117
+ */
1118
+ function analyticsMetricCatalog() {
1119
+ return ANALYTICS_METRIC_KEYS.map((metric) => {
1120
+ const spec = ANALYTICS_METRICS[metric];
1121
+ return {
1122
+ metric,
1123
+ scope: spec.scope,
1124
+ scopeParam: spec.scope === "team" ? "teamId" : "userIds",
1125
+ requires: [...spec.requires],
1126
+ optional: spec.inputs.filter((i) => !spec.requires.includes(i))
1127
+ };
1128
+ });
1129
+ }
1130
+ const ANALYTICS_BODY_KEY = {
1131
+ date: "date",
1132
+ dateStart: "date_start",
1133
+ dateEnd: "date_end",
1134
+ exerciseId: "exercise_id",
1135
+ useMetric: "use_metric"
1136
+ };
1137
+ /**
1138
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
1139
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
1140
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
1141
+ */
1142
+ async function queryAnalytics(client, args) {
1143
+ const spec = ANALYTICS_METRICS[args.metric];
1144
+ const body = {};
1145
+ if (spec.scope === "team") {
1146
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
1147
+ body.teamId = args.teamId;
1148
+ } else {
1149
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
1150
+ body.user_ids = args.userIds.map((u) => String(u));
1151
+ }
1152
+ const inputs = {
1153
+ date: args.date,
1154
+ dateStart: args.dateStart,
1155
+ dateEnd: args.dateEnd,
1156
+ exerciseId: args.exerciseId,
1157
+ useMetric: args.useMetric
1158
+ };
1159
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
1160
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
1161
+ for (const k of spec.inputs) {
1162
+ const v = inputs[k];
1163
+ if (v === void 0) continue;
1164
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
1165
+ }
1166
+ const res = await client.request("POST", spec.path, { body });
1167
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1168
+ return res.data;
1169
+ }
1170
+ //#endregion
1171
+ //#region src/util.ts
1172
+ /**
1173
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
1174
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
1175
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
1176
+ * optional ones lose `undefined` from their value type.
1177
+ *
1178
+ * Example:
1179
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
1180
+ */
1181
+ function definedProps(obj) {
1182
+ const result = {};
1183
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
1184
+ return result;
1185
+ }
1186
+ //#endregion
863
1187
  //#region src/workout-encode.ts
864
1188
  const LEADERBOARD_TYPE = {
865
1189
  completion: 0,
@@ -1426,4 +1750,4 @@ var ExerciseLibrary = class {
1426
1750
  }
1427
1751
  };
1428
1752
  //#endregion
1429
- export { ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseLogPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, coerceInt, coerceNum, collectAdvisories, createPersonalWorkout, deleteComment, exerciseUnits, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchStreams, fetchWorkingMaxes, findSavedWorkoutSet, isRecord, logAthleteSet, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, publishSession, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
1753
+ 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, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAthleteSet, logForAthlete, loginTrainHeroic, makeExercise, mapPool, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "0.6.4",
3
+ "version": "1.0.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": "0.6.4"
30
+ "@trainheroic-unofficial/dto": "1.0.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",