@trainheroic-unofficial/js 2.0.2 → 2.1.1

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
@@ -110,6 +110,21 @@ const client = new TrainHeroicClient(
110
110
  If the reused token has expired, the next request gets a 401/403; the client logs in once with
111
111
  the credentials, retries, and updates `client.sessionId` to the new token.
112
112
 
113
+ The optional fourth constructor argument can persist renewed sessions and report final HTTP
114
+ failures without coupling the SDK to a telemetry vendor:
115
+
116
+ ```ts
117
+ const client = new TrainHeroicClient(email, password, savedSession, {
118
+ onSession: saveSession,
119
+ onHttpError: (error) => telemetry.captureException(error),
120
+ });
121
+ ```
122
+
123
+ `onHttpError` receives a `TrainHeroicHttpError` containing only the method, status, and host.
124
+ Paths, query strings, bodies, credentials, and session tokens are excluded. A transient 401/403
125
+ that succeeds after automatic re-login does not call the hook, and synchronous or asynchronous
126
+ hook failures never change the request result.
127
+
113
128
  ## Two entry points
114
129
 
115
130
  ```ts
package/dist/index.d.mts CHANGED
@@ -2,6 +2,21 @@ import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from
2
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";
3
3
  import { ZodType } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
+ //#region src/http-error.d.ts
6
+ /**
7
+ * A final non-2xx response from TrainHeroic. The error deliberately carries only request
8
+ * metadata that is safe to send to telemetry: never the path, query string, request body,
9
+ * response body, credentials, or session token.
10
+ */
11
+ declare class TrainHeroicHttpError extends Error {
12
+ readonly name = "TrainHeroicHttpError";
13
+ readonly method: string;
14
+ readonly status: number;
15
+ readonly host: string;
16
+ constructor(method: string, url: string, status: number);
17
+ }
18
+ type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
19
+ //#endregion
5
20
  //#region src/auth.d.ts
6
21
  type TrainHeroicSession = {
7
22
  thUserId: number;
@@ -9,13 +24,17 @@ type TrainHeroicSession = {
9
24
  scope: string;
10
25
  role: string;
11
26
  };
27
+ type LoginOptions = {
28
+ /** Called for every non-2xx login response; callback failures never change the result. */
29
+ onHttpError?: TrainHeroicHttpErrorHandler;
30
+ };
12
31
  /**
13
32
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
14
33
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
15
34
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
16
35
  * is sent as the `session-token` header and works against both API hosts.
17
36
  */
18
- declare function loginTrainHeroic(email: string, password: string): Promise<TrainHeroicSession | null>;
37
+ declare function loginTrainHeroic(email: string, password: string, options?: LoginOptions): Promise<TrainHeroicSession | null>;
19
38
  //#endregion
20
39
  //#region src/client.d.ts
21
40
  declare class TrainHeroicAuthError extends Error {
@@ -39,6 +58,12 @@ type ClientOptions = {
39
58
  * instead of logging in again.
40
59
  */
41
60
  onSession?: (sessionId: string) => void;
61
+ /**
62
+ * Called once when a login or API request finishes with a non-2xx response. Transient 401/403
63
+ * API responses that succeed after the built-in re-login are not reported. The callback is
64
+ * best-effort: telemetry failures never change the API result returned to the caller.
65
+ */
66
+ onHttpError?: TrainHeroicHttpErrorHandler;
42
67
  };
43
68
  /**
44
69
  * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
@@ -211,20 +236,6 @@ declare function fetchAthleteWorkoutsChunked(client: TrainHeroicClient, startDat
211
236
  concurrency?: number;
212
237
  onProgress?: (done: number, total: number) => void;
213
238
  }): Promise<ProgramWorkout[]>;
214
- /**
215
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
216
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
217
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
218
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
219
- */
220
- declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
221
- /**
222
- * A coach's month view of a roster athlete's logged sessions
223
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
224
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
225
- * `userId` in each row is the roster athlete, not the calling coach.
226
- */
227
- declare function fetchCoachAthleteCalendarSummary(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<unknown[]>;
228
239
  declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number, opts?: {
229
240
  page?: number;
230
241
  pageSize?: number;
@@ -317,6 +328,50 @@ declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId:
317
328
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
318
329
  declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
319
330
  //#endregion
331
+ //#region src/coach-athlete-calendar.d.ts
332
+ /**
333
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
334
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
335
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
336
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
337
+ */
338
+ declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
339
+ /**
340
+ * A coach's month view of a roster athlete's logged sessions
341
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
342
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
343
+ * `userId` in each row is the roster athlete, not the calling coach.
344
+ */
345
+ declare function fetchCoachAthleteCalendarSummary(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<unknown[]>;
346
+ /** A roster athlete's coach-writable calendar (from `GET /v5/calendars/athletes/{id}`). */
347
+ type CoachAthleteCalendar = {
348
+ programId: number;
349
+ title: string;
350
+ /** Program type: 5 = individual athlete calendar, 4 = coach own calendar (observed). */
351
+ type: number | null;
352
+ groupId: number | null;
353
+ };
354
+ /**
355
+ * Resolve a roster athlete's coach-writable calendar program id
356
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
357
+ *
358
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
359
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
360
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
361
+ * from athlete-created `personal_cal` ad-hoc sessions.
362
+ */
363
+ declare function fetchCoachAthleteCalendar(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<CoachAthleteCalendar>;
364
+ /**
365
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
366
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
367
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
368
+ */
369
+ declare function resolveBuildProgramId(client: TrainHeroicClient, args: {
370
+ programId?: number;
371
+ athleteId?: number;
372
+ date?: string;
373
+ }): Promise<number>;
374
+ //#endregion
320
375
  //#region src/exercise-set-payload.d.ts
321
376
  type SetWriteMode = "log" | "prescribe";
322
377
  type ExerciseSetInput = {
@@ -734,6 +789,19 @@ declare function inviteAthletes(client: TrainHeroicClient, args: {
734
789
  invited: string[];
735
790
  result: unknown;
736
791
  }>;
792
+ /**
793
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
794
+ *
795
+ * The live API accepts `group_program` to point the team at an existing parent program /
796
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
797
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
798
+ * the current title first so callers can re-link without renaming.
799
+ */
800
+ declare function updateTeam(client: TrainHeroicClient, args: {
801
+ teamId: number;
802
+ title?: string;
803
+ groupProgram?: number;
804
+ }): Promise<unknown>;
737
805
  /**
738
806
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
739
807
  * The API wants the target date as a structured object (with weekday and an isToday flag),
@@ -913,4 +981,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
913
981
  stats(): Promise<Record<string, unknown>>;
914
982
  }
915
983
  //#endregion
916
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, 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, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
984
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, 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 };
package/dist/index.mjs CHANGED
@@ -1,6 +1,34 @@
1
1
  import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  import { z } from "zod";
3
3
  export * from "@trainheroic-unofficial/dto";
4
+ //#region src/http-error.ts
5
+ /**
6
+ * A final non-2xx response from TrainHeroic. The error deliberately carries only request
7
+ * metadata that is safe to send to telemetry: never the path, query string, request body,
8
+ * response body, credentials, or session token.
9
+ */
10
+ var TrainHeroicHttpError = class extends Error {
11
+ name = "TrainHeroicHttpError";
12
+ method;
13
+ status;
14
+ host;
15
+ constructor(method, url, status) {
16
+ const parsed = new URL(url);
17
+ const normalizedMethod = method.toUpperCase();
18
+ super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
19
+ this.method = normalizedMethod;
20
+ this.status = status;
21
+ this.host = parsed.host;
22
+ }
23
+ };
24
+ /** Call observability hooks without allowing them to change SDK behavior. */
25
+ function notifyHttpError(handler, method, url, status) {
26
+ if (!handler) return;
27
+ try {
28
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
29
+ } catch {}
30
+ }
31
+ //#endregion
4
32
  //#region src/auth.ts
5
33
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
6
34
  /**
@@ -22,8 +50,9 @@ function authUrl() {
22
50
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
23
51
  * is sent as the `session-token` header and works against both API hosts.
24
52
  */
25
- async function loginTrainHeroic(email, password) {
26
- const res = await fetch(authUrl(), {
53
+ async function loginTrainHeroic(email, password, options = {}) {
54
+ const url = authUrl();
55
+ const res = await fetch(url, {
27
56
  method: "POST",
28
57
  headers: {
29
58
  "content-type": "application/x-www-form-urlencoded",
@@ -34,7 +63,10 @@ async function loginTrainHeroic(email, password) {
34
63
  password
35
64
  }).toString()
36
65
  });
37
- if (!res.ok) return null;
66
+ if (!res.ok) {
67
+ notifyHttpError(options.onHttpError, "POST", url, res.status);
68
+ return null;
69
+ }
38
70
  const data = await res.json().catch(() => null);
39
71
  if (!data || typeof data.id !== "number" || !data.session_id) return null;
40
72
  return {
@@ -77,6 +109,7 @@ var TrainHeroicClient = class {
77
109
  #email;
78
110
  #password;
79
111
  #onSession;
112
+ #onHttpError;
80
113
  #sessionId;
81
114
  #loginInFlight = null;
82
115
  constructor(email, password, sessionId = null, options = {}) {
@@ -84,6 +117,7 @@ var TrainHeroicClient = class {
84
117
  this.#password = password;
85
118
  this.#sessionId = sessionId;
86
119
  this.#onSession = options.onSession;
120
+ this.#onHttpError = options.onHttpError;
87
121
  }
88
122
  get sessionId() {
89
123
  return this.#sessionId;
@@ -98,7 +132,7 @@ var TrainHeroicClient = class {
98
132
  }
99
133
  }
100
134
  async #login() {
101
- const session = await loginTrainHeroic(this.#email, this.#password);
135
+ const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
102
136
  if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
103
137
  this.#sessionId = session.sessionId;
104
138
  try {
@@ -115,6 +149,7 @@ var TrainHeroicClient = class {
115
149
  session = await this.#ensureSession();
116
150
  res = await this.#send(method, url, session, options.body);
117
151
  }
152
+ if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
118
153
  const text = await res.text();
119
154
  let data = text;
120
155
  if (text.length > 0) try {
@@ -356,7 +391,7 @@ async function getJson(client, path, label) {
356
391
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
357
392
  return res.data;
358
393
  }
359
- async function getArray(client, path, label) {
394
+ async function getArray$1(client, path, label) {
360
395
  const res = await client.request("GET", path);
361
396
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
362
397
  return res.data;
@@ -439,10 +474,10 @@ function fetchAthletePrefs(client) {
439
474
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
440
475
  }
441
476
  function fetchWorkingMaxes(client) {
442
- return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
477
+ return getArray$1(client, "/2.0/athlete/workingMax", "athlete working maxes");
443
478
  }
444
479
  function fetchExerciseHistoryList(client) {
445
- return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
480
+ return getArray$1(client, "/v5/users/exercises/history", "athlete exercise history list");
446
481
  }
447
482
  /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
448
483
  async function searchExerciseHistory(client, query, limit = 20) {
@@ -452,7 +487,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
452
487
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
453
488
  }
454
489
  function fetchPersonalRecords(client, exerciseId) {
455
- return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
490
+ return getArray$1(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
456
491
  }
457
492
  /** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
458
493
  function fetchExerciseStats(client, exerciseId, userId, date) {
@@ -460,7 +495,7 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
460
495
  }
461
496
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
462
497
  function fetchAthleteWorkouts(client, startDate, endDate) {
463
- return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
498
+ return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
464
499
  }
465
500
  /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
466
501
  function shiftDate(iso, days) {
@@ -522,24 +557,6 @@ async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}
522
557
  return page;
523
558
  }));
524
559
  }
525
- /**
526
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
527
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
528
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
529
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
530
- */
531
- function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
532
- return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
533
- }
534
- /**
535
- * A coach's month view of a roster athlete's logged sessions
536
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
537
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
538
- * `userId` in each row is the roster athlete, not the calling coach.
539
- */
540
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
541
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
542
- }
543
560
  function fetchLeaderboard(client, workoutId, opts = {}) {
544
561
  const qs = new URLSearchParams();
545
562
  if (opts.page !== void 0) qs.set("page", String(opts.page));
@@ -1004,6 +1021,70 @@ function presentExerciseHistory(detail) {
1004
1021
  };
1005
1022
  }
1006
1023
  //#endregion
1024
+ //#region src/coach-athlete-calendar.ts
1025
+ async function getArray(client, path, label) {
1026
+ const res = await client.request("GET", path);
1027
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
1028
+ return res.data;
1029
+ }
1030
+ /**
1031
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1032
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1033
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1034
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1035
+ */
1036
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1037
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1038
+ }
1039
+ /**
1040
+ * A coach's month view of a roster athlete's logged sessions
1041
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1042
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1043
+ * `userId` in each row is the roster athlete, not the calling coach.
1044
+ */
1045
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1046
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1047
+ }
1048
+ /**
1049
+ * Resolve a roster athlete's coach-writable calendar program id
1050
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
1051
+ *
1052
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
1053
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
1054
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
1055
+ * from athlete-created `personal_cal` ad-hoc sessions.
1056
+ */
1057
+ async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
1058
+ const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
1059
+ const res = await client.request("GET", path);
1060
+ if (!res.ok) {
1061
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1062
+ throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
1063
+ }
1064
+ if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
1065
+ const programId = coerceInt(res.data.id);
1066
+ if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
1067
+ return {
1068
+ programId,
1069
+ title: str(res.data.title) ?? "",
1070
+ type: coerceInt(res.data.type),
1071
+ groupId: coerceInt(res.data.group_id)
1072
+ };
1073
+ }
1074
+ /**
1075
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
1076
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
1077
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
1078
+ */
1079
+ async function resolveBuildProgramId(client, args) {
1080
+ if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
1081
+ if (args.programId !== void 0) return args.programId;
1082
+ if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
1083
+ if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
1084
+ const [y, m] = parseWorkoutDate(args.date);
1085
+ return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1086
+ }
1087
+ //#endregion
1007
1088
  //#region src/exercise-set-payload.ts
1008
1089
  function slotData(exercise, key) {
1009
1090
  const value = exercise?.[key];
@@ -1960,8 +2041,10 @@ function unitAdvisory(blockTitle, ex, defaults) {
1960
2041
  if (ex.weight !== void 0 && ex.weight !== null) {
1961
2042
  const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
1962
2043
  const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
1963
- if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
1964
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2044
+ if (sentP2 !== effP2) {
2045
+ if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2046
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2047
+ }
1965
2048
  }
1966
2049
  return {
1967
2050
  notes,
@@ -2008,7 +2091,7 @@ async function collectAdvisories(blocks, index) {
2008
2091
  function calendarWriteError(method, path, status, detail) {
2009
2092
  const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2010
2093
  if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2011
- return /* @__PURE__ */ new Error(`${base}. This often means the program is another athlete's Coach Plan / personal calendar (personal_cal), which the coach calendar write endpoints do not support — workout_build and session_copy work on team/group programs (and the coach's own personal calendar), but there is currently no coach-facing tool to create sessions on another athlete's personal calendar.`);
2094
+ return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
2012
2095
  }
2013
2096
  async function req(client, method, path, body) {
2014
2097
  const res = await client.request(method, path, body === void 0 ? void 0 : { body });
@@ -2198,6 +2281,36 @@ async function inviteAthletes(client, args) {
2198
2281
  };
2199
2282
  }
2200
2283
  /**
2284
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
2285
+ *
2286
+ * The live API accepts `group_program` to point the team at an existing parent program /
2287
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
2288
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
2289
+ * the current title first so callers can re-link without renaming.
2290
+ */
2291
+ async function updateTeam(client, args) {
2292
+ if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
2293
+ let title = args.title;
2294
+ if (title === void 0) {
2295
+ const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
2296
+ if (!existing.ok) {
2297
+ const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
2298
+ throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
2299
+ }
2300
+ const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
2301
+ title = typeof rec?.title === "string" ? rec.title : "";
2302
+ if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
2303
+ }
2304
+ const body = { title };
2305
+ if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
2306
+ const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
2307
+ if (!res.ok) {
2308
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2309
+ throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
2310
+ }
2311
+ return res.data;
2312
+ }
2313
+ /**
2201
2314
  * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2202
2315
  * The API wants the target date as a structured object (with weekday and an isToday flag),
2203
2316
  * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
@@ -2903,4 +3016,4 @@ var ExerciseLibrary = class {
2903
3016
  }
2904
3017
  };
2905
3018
  //#endregion
2906
- export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, 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, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
3019
+ export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "2.0.2",
3
+ "version": "2.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,10 +27,10 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "2.0.2"
30
+ "@trainheroic-unofficial/dto": "2.1.1"
31
31
  },
32
32
  "devDependencies": {
33
- "@types/node": "^26.1.2",
33
+ "@types/node": "^26.2.0",
34
34
  "tsdown": "^0.22.14",
35
35
  "vitest": "^4.1.10"
36
36
  },