@trainheroic-unofficial/js 4.2.0 → 4.3.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
@@ -221,9 +221,6 @@ import { buildSession, type BlockSpec } from "@trainheroic-unofficial/js";
221
221
 
222
222
  const { match } = await library.resolve("Back Squat");
223
223
  if (!match) throw new Error("Resolve to a single exercise before building.");
224
- if (match.units[0] !== "reps" || match.units[1] !== "lb") {
225
- throw new Error("Choose an exercise with reps and pounds as its fixed units.");
226
- }
227
224
 
228
225
  const blocks: BlockSpec[] = [
229
226
  {
@@ -257,14 +254,16 @@ Each exercise needs an `id`; `sets`, `reps`, `weight`, `rpe`, and a per-exercise
257
254
  optional. `reps` and `weight` take a scalar (broadcast across every set) or a per-set array
258
255
  like `reps: [5, 5, 3]`. State `primaryUnit` for `reps` and `secondaryUnit` for `weight`.
259
256
  The full field list is `ExerciseSpec` / `BlockSpec` in
260
- [`@trainheroic-unofficial/dto`](../dto). `buildSession` checks those units against the
261
- exercise library and rejects a mismatch before writing.
257
+ [`@trainheroic-unofficial/dto`](../dto). `buildSession` keeps an exercise's default unit when
258
+ the stated unit matches it and sets any other stated unit on this session, as described under "The workout encoder".
262
259
 
263
260
  `buildSession` returns `{ pwId, workoutId, advisories }`: `pwId` is the program-workout id (the
264
261
  placement of the session in the program, which is the handle subsequent calls take), and
265
262
  `workoutId` is the underlying workout id. Use `pwId` with `readSession(client, programId, date, pwId)`
266
- to read the session back. `publishSession(client, pwId)` publishes it later;
267
- `removeSession(client, programId, pwId)` deletes it.
263
+ to read the session back; the read-back also carries `workoutId`. `publishSession(client, pwId)`
264
+ publishes it later; `removeSession(client, programId, pwId)` deletes it.
265
+ `saveSessionAsTemplate(client, { workoutId, pwId, title })` copies the session into the coach's
266
+ session library.
268
267
 
269
268
  ## Reading athlete training
270
269
 
@@ -314,14 +313,23 @@ console.log(analyticsMetricCatalog());
314
313
  `buildSession` calls the encoder for you; you only deal with it directly to preview values.
315
314
  TrainHeroic's exercise payload expects every parameter slot present, so the encoder fills all
316
315
  of them (empty slots included) to avoid an HTTP 500. A scalar prescription is broadcast across
317
- the set count. RPE goes into the instruction text because the API coerces a numeric slot to
318
- load. Each populated slot in a spec states its intended unit. `collectAdvisories` rejects a
319
- unit that differs from the exercise's fixed parameter type before a workout is written.
320
-
321
- `buildSession` calls `collectAdvisories(blocks, index)` before its first write and returns
322
- its non-blocking notes and warnings in `advisories`. Call `collectAdvisories` directly to
323
- preview validation without writing a workout. Validation fetches current units from
324
- TrainHeroic; an unavailable library response stops the build.
316
+ the set count. The `rpe` field goes into the instruction text; to prescribe RPE as a structured
317
+ load, put the values in `weight` with `secondaryUnit: "RPE"`. Each populated slot in a spec
318
+ states its unit, and `resolveExerciseUnits` maps that unit to a TrainHeroic param type. It keeps
319
+ the exercise's library default when the default already has the stated unit, and otherwise uses
320
+ the stated unit's own type, so a spec can prescribe `%max` on a pounds lift or meters on a miles
321
+ exercise. It throws before any write when a unit is unknown, conflicts with an explicit
322
+ `param_N_type`, or names two types (`sec` and `in`; set `param_N_type` to choose).
323
+
324
+ TrainHeroic stores a newly inserted exercise row with the library's param types whatever the
325
+ request says, and keeps the requested types when the same row is saved again by id (the coach
326
+ web app's unit picker works this way). `buildSession` therefore re-saves by id each row whose
327
+ stored types differ from the resolved ones, and throws if TrainHeroic still does not keep them.
328
+
329
+ `buildSession` returns the resolver's non-blocking notes and warnings in `advisories`; a note
330
+ names each unit set in place of an exercise's default. Call `collectAdvisories` to preview
331
+ validation without writing a workout. Resolution fetches current defaults from TrainHeroic; an
332
+ unavailable library response stops the build.
325
333
 
326
334
  ## Develop
327
335
 
package/dist/index.d.mts CHANGED
@@ -1,9 +1,8 @@
1
- import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
- import { Advisory, AthleteExerciseNoteOutput, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutNoteOutput, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
1
+ import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-TkOsfh5m.mjs";
2
+ import { Advisory, AthleteExerciseNoteOutput, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutNoteOutput, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionSaveAsTemplate, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
3
3
  import { chunk } from "es-toolkit/array";
4
4
  import { ZodType } from "zod";
5
5
  export * from "@trainheroic-unofficial/dto";
6
- //#region src/http-error.d.ts
7
6
  type JsonScalar = boolean | number | string | null;
8
7
  type RequestBodySummary = {
9
8
  type: "array";
@@ -51,12 +50,8 @@ export declare class TrainHeroicUnavailableError extends Error {
51
50
  constructor(status: number);
52
51
  }
53
52
  type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
54
- //#endregion
55
- //#region src/transport.d.ts
56
53
  /** The HTTP seam used by the SDK. It defaults to global `fetch` and stays injectable for hosts. */
57
54
  type TrainHeroicTransport = (url: string, init: RequestInit) => Promise<Response>;
58
- //#endregion
59
- //#region src/auth.d.ts
60
55
  export type TrainHeroicSession = {
61
56
  thUserId: number;
62
57
  sessionId: string;
@@ -78,8 +73,6 @@ export type LoginOptions = {
78
73
  * is sent as the `session-token` header and works against both API hosts.
79
74
  */
80
75
  export declare function loginTrainHeroic(email: string, password: string, options?: LoginOptions): Promise<TrainHeroicSession | null>;
81
- //#endregion
82
- //#region src/client.d.ts
83
76
  export declare class TrainHeroicAuthError extends Error {
84
77
  name: string;
85
78
  }
@@ -130,21 +123,17 @@ export declare class TrainHeroicClient {
130
123
  get sessionId(): string | null;
131
124
  request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<ClientResult<T>>;
132
125
  }
133
- //#endregion
134
- //#region src/response-check.d.ts
135
126
  /**
136
127
  * Validate an API response against its (loose) expected shape and warn once on drift.
137
128
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
138
129
  * when TrainHeroic renames or drops a field we read.
139
130
  */
140
131
  export declare function checkResponse(schema: ZodType, data: unknown, label: string): void;
141
- //#endregion
142
- //#region src/exercise-util.d.ts
143
132
  /**
144
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
145
- * (the API forces param_1_type/param_2_type back to the library default on save), so
146
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
147
- * metric workout. Keep in sync with the workout builder's unit table.
133
+ * Display labels for TrainHeroic parameter types. Each library exercise has a default type per
134
+ * slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
135
+ * A session can set a different type on an exercise; the workout builder maps a stated unit
136
+ * back to its type code through this table, so keep it in sync with the builder's unit aliases.
148
137
  */
149
138
  export declare const PARAM_UNIT: Readonly<Record<number, string | null>>;
150
139
  export declare const PARAM_NONE = 0;
@@ -159,7 +148,7 @@ export declare function coerceInt(value: unknown): number | null;
159
148
  export declare function coerceNum(value: unknown): number | null;
160
149
  export declare function unitLabel(paramType: unknown): string | null;
161
150
  /**
162
- * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
151
+ * Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
163
152
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
164
153
  * by role. A null entry is an unset slot.
165
154
  */
@@ -251,8 +240,6 @@ export interface ExerciseIndex {
251
240
  recordDelete(id: number): Promise<void>;
252
241
  stats(): Promise<Record<string, unknown>>;
253
242
  }
254
- //#endregion
255
- //#region src/athlete.d.ts
256
243
  /**
257
244
  * The logged-in account's numeric user id (the athlete warehouse's tenant key, and a required
258
245
  * query arg for several athlete endpoints). Works from any session — coach or athlete — and
@@ -425,8 +412,6 @@ export declare function summarizeAthleteWorkouts(list: readonly AthleteWorkoutVi
425
412
  export declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId: number, year: number, month: number): CoachAthleteTraining;
426
413
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
427
414
  export declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
428
- //#endregion
429
- //#region src/exercise-history.d.ts
430
415
  /**
431
416
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
432
417
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -435,8 +420,6 @@ export declare function presentExerciseHistory(detail: ExerciseHistoryDetail): P
435
420
  * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
436
421
  */
437
422
  export declare function historyInRange(presented: PresentedExerciseHistory, since: string | undefined, until: string | undefined): PresentedExerciseHistory;
438
- //#endregion
439
- //#region src/coach-athlete-calendar.d.ts
440
423
  /**
441
424
  * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
442
425
  * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
@@ -444,11 +427,20 @@ export declare function historyInRange(presented: PresentedExerciseHistory, sinc
444
427
  * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
445
428
  */
446
429
  export declare function fetchCoachAthleteWorkouts(client: TrainHeroicClient, athleteId: number, startDate: string, endDate: string): Promise<ProgramWorkout[]>;
430
+ /** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
431
+ export declare class CoachMonthSummaryError extends Error {
432
+ readonly name = "CoachMonthSummaryError";
433
+ readonly status: number;
434
+ constructor(message: string, status: number);
435
+ }
447
436
  /**
448
437
  * A coach's month view of a roster athlete's logged sessions
449
438
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
450
439
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
451
440
  * `userId` in each row is the roster athlete, not the calling coach.
441
+ *
442
+ * TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
443
+ * read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
452
444
  */
453
445
  export declare function fetchCoachAthleteCalendarSummary(client: TrainHeroicClient, athleteId: number, year: number, month: number): Promise<unknown[]>;
454
446
  /** A roster athlete's coach-writable calendar (from `GET /v5/calendars/athletes/{id}`). */
@@ -479,8 +471,6 @@ export declare function resolveBuildProgramId(client: TrainHeroicClient, args: {
479
471
  athleteId?: number;
480
472
  date?: string;
481
473
  }): Promise<number>;
482
- //#endregion
483
- //#region src/exercise-set-payload.d.ts
484
474
  type SetWriteMode = "log" | "prescribe";
485
475
  type ExerciseSetInput = {
486
476
  param1?: number | string;
@@ -503,8 +493,6 @@ type ExerciseSetPayload = Record<string, unknown> & {
503
493
  * full payload and never marks slots or the exercise complete.
504
494
  */
505
495
  export declare function buildExerciseSetPayload(savedWorkoutSetExerciseId: number, savedWorkoutSetId: number, workoutSetExerciseId: number, results: readonly ExerciseSetInput[], mode: SetWriteMode, existing?: Record<string, unknown>): ExerciseSetPayload;
506
- //#endregion
507
- //#region src/athlete-set-write.d.ts
508
496
  /**
509
497
  * One set of entered values for a single exercise within a saved workout set.
510
498
  * `param1` and `param2` correspond to the exercise's first and second parameter types
@@ -777,8 +765,6 @@ export declare function logSessionForAthlete(client: TrainHeroicClient, args: {
777
765
  date: string;
778
766
  exercises: readonly SessionExercise[];
779
767
  }): Promise<LogSessionResult>;
780
- //#endregion
781
- //#region src/athlete-workout-note.d.ts
782
768
  /**
783
769
  * PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
784
770
  * workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
@@ -791,8 +777,6 @@ export declare function setAthleteWorkoutNote(client: TrainHeroicClient, args: {
791
777
  notes?: string | undefined;
792
778
  rpe?: number | undefined;
793
779
  }): Promise<AthleteWorkoutNoteOutput>;
794
- //#endregion
795
- //#region src/athlete-exercise-note.d.ts
796
780
  /**
797
781
  * PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
798
782
  * "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
@@ -803,8 +787,6 @@ export declare function setAthleteExerciseNote(client: TrainHeroicClient, args:
803
787
  savedWorkoutSetExerciseId: number | string;
804
788
  notes: string;
805
789
  }): Promise<AthleteExerciseNoteOutput>;
806
- //#endregion
807
- //#region src/workout-export.d.ts
808
790
  export type WorkoutExportFormat = "json" | "csv" | "text";
809
791
  /** A serialized export ready to write to a file or hand to a browser download. */
810
792
  export type SerializedExport = {
@@ -827,8 +809,6 @@ export declare function workoutsToText(workouts: readonly WorkoutHistoryExport[]
827
809
  export declare function serializeWorkoutHistory(workouts: readonly WorkoutHistoryExport[], format: WorkoutExportFormat, opts?: {
828
810
  filenameBase?: string;
829
811
  }): SerializedExport;
830
- //#endregion
831
- //#region src/main-lifts.d.ts
832
812
  export type MainLiftFamilyKey = "cleanjerk" | "snatch" | "deadlift" | "squat" | "bench" | "overhead";
833
813
  export type MainLiftFamily = {
834
814
  key: MainLiftFamilyKey;
@@ -910,8 +890,6 @@ export declare function fetchRosterMainLiftPRs(client: TrainHeroicClient, opts?:
910
890
  now?: Date;
911
891
  concurrency?: number;
912
892
  }): Promise<AthleteMainLiftPRs[]>;
913
- //#endregion
914
- //#region src/coach.d.ts
915
893
  export declare const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
916
894
  export declare const PROGRAM_KINDS: readonly ["calendar", "fixed"];
917
895
  export type ProgramKind = (typeof PROGRAM_KINDS)[number];
@@ -1074,10 +1052,17 @@ export declare function teamVolume(client: TrainHeroicClient, args: {
1074
1052
  }): Promise<TeamVolumeReport>;
1075
1053
  /** Create a reusable session template in the coach library (`POST /v5/sessions/template`). */
1076
1054
  export declare function createSessionTemplate(client: TrainHeroicClient, args: SessionTemplateCreate): Promise<Record<string, unknown>>;
1055
+ /**
1056
+ * Copy an existing calendar session, with its blocks and exercises, into the coach's session
1057
+ * library as a new template
1058
+ * (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
1059
+ * the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
1060
+ * the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
1061
+ * has no `id`, or when the two ids are swapped.
1062
+ */
1063
+ export declare function saveSessionAsTemplate(client: TrainHeroicClient, args: SessionSaveAsTemplate): Promise<Record<string, unknown>>;
1077
1064
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
1078
1065
  export declare const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
1079
- //#endregion
1080
- //#region src/util.d.ts
1081
1066
  /**
1082
1067
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
1083
1068
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -1088,8 +1073,6 @@ export declare const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&p
1088
1073
  * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
1089
1074
  */
1090
1075
  export declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclude<T[K], undefined>; };
1091
- //#endregion
1092
- //#region src/workout-encode.d.ts
1093
1076
  type AdvisoryIndex = Pick<ExerciseIndex, "currentDefaultsMany">;
1094
1077
  export type SetSplit = {
1095
1078
  blockTitle: string;
@@ -1128,19 +1111,37 @@ export declare const BLOCK_TYPE_HYPERTROPHY = 2;
1128
1111
  */
1129
1112
  export declare function defaultBlockType(block: BlockSpec): number;
1130
1113
  export declare function buildBlockPayload(blocks: readonly BlockSpec[], workoutId: number): Array<Record<string, unknown>>;
1131
- /** Flag spec params the API will silently override to the exercise's fixed units. */
1132
- export declare function unitAdvisory(blockTitle: string, ex: ExerciseSpec, defaults: {
1133
- param1: number | null;
1134
- param2: number | null;
1135
- }): Advisory;
1136
1114
  /**
1137
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
1138
- * then collect non-blocking advisories. The write path calls this before creating a workout;
1139
- * TrainHeroic silently replaces mismatched types.
1115
+ * The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
1116
+ * other than the library default. This is the one definition of a unit override: the advisory
1117
+ * notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
1118
+ * exactly these types.
1119
+ */
1120
+ export declare function overriddenSlots(ex: ExerciseSpec, defaults: ExerciseDefaults): Array<1 | 2>;
1121
+ /**
1122
+ * Describe how a resolved exercise's units relate to its library defaults, and flag spec
1123
+ * fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
1124
+ * (from `resolveExerciseUnits`).
1125
+ */
1126
+ export declare function unitAdvisory(label: string, ex: ExerciseSpec, defaults: ExerciseDefaults): Advisory;
1127
+ /** A block list with resolved param types, the library defaults used, and advisories. */
1128
+ export type ResolvedUnits = {
1129
+ blocks: BlockSpec[];
1130
+ defaultsById: Map<number, ExerciseDefaults>;
1131
+ advisories: Advisory;
1132
+ };
1133
+ /**
1134
+ * Resolve every exercise's param types against current TrainHeroic exercise data and collect
1135
+ * non-blocking advisories. Throws, before anything is written, when a populated slot has no
1136
+ * stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
1137
+ * returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
1138
+ */
1139
+ export declare function resolveExerciseUnits(blocks: readonly BlockSpec[], index: AdvisoryIndex): Promise<ResolvedUnits>;
1140
+ /**
1141
+ * Validate units and collect advisories without writing a workout. This is the preview entry
1142
+ * point; `resolveExerciseUnits` also returns the resolved blocks that `buildSession` writes.
1140
1143
  */
1141
1144
  export declare function collectAdvisories(blocks: readonly BlockSpec[], index: AdvisoryIndex): Promise<Advisory>;
1142
- //#endregion
1143
- //#region src/workout-session.d.ts
1144
1145
  export type BuildOptions = {
1145
1146
  programId: number;
1146
1147
  blocks: BlockSpec[];
@@ -1175,8 +1176,6 @@ export declare function setSessionInstruction(client: TrainHeroicClient, workout
1175
1176
  export declare function removeSession(client: TrainHeroicClient, programId: number, pwId: number): Promise<void>;
1176
1177
  export declare function publishSession(client: TrainHeroicClient, pwId: number): Promise<void>;
1177
1178
  export declare function readSession(client: TrainHeroicClient, programId: number, date: WorkoutDate, pwId: number): Promise<ReadResult>;
1178
- //#endregion
1179
- //#region src/messaging.d.ts
1180
1179
  /** Live list of chat streams, flattened to (stream, kind) tuples. */
1181
1180
  export declare function fetchStreams(client: TrainHeroicClient): Promise<Array<{
1182
1181
  stream: Record<string, unknown>;
@@ -1190,8 +1189,6 @@ export declare function buildCommentPayload(streamId: number, text: string, repl
1190
1189
  export declare function sendComment(client: TrainHeroicClient, streamId: number, text: string, replyTo?: number | null): Promise<Record<string, unknown>>;
1191
1190
  export declare function deleteComment(client: TrainHeroicClient, streamId: number, commentId: number): Promise<unknown>;
1192
1191
  export declare function readLive(client: TrainHeroicClient, streamId: number, limit?: number, afterCommentId?: number): Promise<unknown[]>;
1193
- //#endregion
1194
- //#region src/exercise-index.d.ts
1195
1192
  /** Read current parameter types without refreshing or trusting the search mirror. */
1196
1193
  export declare function fetchCurrentExerciseDefaults(client: TrainHeroicClient, ids: readonly number[]): Promise<Map<number, ExerciseDefaults>>;
1197
1194
  /**
@@ -1215,5 +1212,4 @@ export declare class ExerciseLibrary implements ExerciseIndex {
1215
1212
  recordDelete(id: number): Promise<void>;
1216
1213
  stats(): Promise<Record<string, unknown>>;
1217
1214
  }
1218
- //#endregion
1219
1215
  export { type ExerciseSetInput, type ExerciseSetPayload, LibraryCache, LibrarySnapshot, MemoryLibraryCache, type RequestBodySummary, type SetWriteMode, type TrainHeroicHttpErrorDiagnostics, type TrainHeroicHttpErrorHandler, type TrainHeroicTransport, chunk };
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema,
2
2
  import { chunk, uniq } from "es-toolkit/array";
3
3
  import { z } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
- //#region src/date-window.ts
5
+ // src/date-window.ts
6
6
  const DAY_MS = 864e5;
7
7
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
8
8
  const MAX_DATE_WINDOWS = 100;
@@ -35,8 +35,7 @@ function splitDateRange(start, end, maxDays) {
35
35
  });
36
36
  return windows;
37
37
  }
38
- //#endregion
39
- //#region src/http-error.ts
38
+ // src/http-error.ts
40
39
  const MAX_REQUEST_KEYS = 50;
41
40
  const MAX_RESPONSE_DEPTH = 4;
42
41
  const MAX_RESPONSE_KEYS = 20;
@@ -272,11 +271,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
272
271
  Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
273
272
  } catch {}
274
273
  }
275
- //#endregion
276
- //#region src/transport.ts
274
+ // src/transport.ts
277
275
  const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
278
- //#endregion
279
- //#region src/auth.ts
276
+ // src/auth.ts
280
277
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
281
278
  /**
282
279
  * The login endpoint, allowing an env override so a test harness can authenticate against a local
@@ -327,13 +324,12 @@ async function loginTrainHeroic(email, password, options = {}) {
327
324
  role: data.role ?? ""
328
325
  };
329
326
  }
330
- //#endregion
331
- //#region src/exercise-util.ts
327
+ // src/exercise-util.ts
332
328
  /**
333
- * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
334
- * (the API forces param_1_type/param_2_type back to the library default on save), so
335
- * resolve/search surface it to stop callers picking, say, the miles "Run" for a
336
- * metric workout. Keep in sync with the workout builder's unit table.
329
+ * Display labels for TrainHeroic parameter types. Each library exercise has a default type per
330
+ * slot, which resolve/search surface so callers know, say, that stock "Run" defaults to miles.
331
+ * A session can set a different type on an exercise; the workout builder maps a stated unit
332
+ * back to its type code through this table, so keep it in sync with the builder's unit aliases.
337
333
  */
338
334
  const PARAM_UNIT = {
339
335
  0: null,
@@ -382,7 +378,7 @@ function unitLabel(paramType) {
382
378
  return PARAM_UNIT[t] ?? null;
383
379
  }
384
380
  /**
385
- * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
381
+ * Default measurement units for an exercise, ordered by entry slot (param 1, then param 2).
386
382
  * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
387
383
  * by role. A null entry is an unset slot.
388
384
  */
@@ -579,8 +575,7 @@ function createLimiter(max) {
579
575
  function assertPositiveInteger(value, label) {
580
576
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
581
577
  }
582
- //#endregion
583
- //#region src/client.ts
578
+ // src/client.ts
584
579
  const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
585
580
  const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
586
581
  const MAX_REQUEST_CONCURRENCY = 4;
@@ -700,8 +695,7 @@ var TrainHeroicClient = class {
700
695
  return this.#transport(url, init);
701
696
  }
702
697
  };
703
- //#endregion
704
- //#region src/response-check.ts
698
+ // src/response-check.ts
705
699
  /**
706
700
  * Validate an API response against its (loose) expected shape and warn once on drift.
707
701
  * Never throws: callers keep working via defensive coercion. This only surfaces a signal
@@ -714,8 +708,7 @@ function checkResponse(schema, data, label) {
714
708
  const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
715
709
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
716
710
  }
717
- //#endregion
718
- //#region src/athlete.ts
711
+ // src/athlete.ts
719
712
  async function getJson(client, path, label) {
720
713
  const res = await client.request("GET", path);
721
714
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -1451,8 +1444,7 @@ function presentExerciseHistory(detail) {
1451
1444
  }))
1452
1445
  };
1453
1446
  }
1454
- //#endregion
1455
- //#region src/exercise-history.ts
1447
+ // src/exercise-history.ts
1456
1448
  /**
1457
1449
  * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1458
1450
  * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
@@ -1473,8 +1465,7 @@ function historyInRange(presented, since, until) {
1473
1465
  sessions
1474
1466
  };
1475
1467
  }
1476
- //#endregion
1477
- //#region src/coach-athlete-calendar.ts
1468
+ // src/coach-athlete-calendar.ts
1478
1469
  async function getArray(client, path, label) {
1479
1470
  const res = await client.request("GET", path);
1480
1471
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
@@ -1489,14 +1480,34 @@ async function getArray(client, path, label) {
1489
1480
  function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1490
1481
  return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1491
1482
  }
1483
+ /** A failed coach month-summary read; `status` is TrainHeroic's HTTP status. */
1484
+ var CoachMonthSummaryError = class extends Error {
1485
+ name = "CoachMonthSummaryError";
1486
+ status;
1487
+ constructor(message, status) {
1488
+ super(message);
1489
+ this.status = status;
1490
+ }
1491
+ };
1492
1492
  /**
1493
1493
  * A coach's month view of a roster athlete's logged sessions
1494
1494
  * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1495
1495
  * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1496
1496
  * `userId` in each row is the roster athlete, not the calling coach.
1497
+ *
1498
+ * TrainHeroic answers this endpoint with HTTP 500 for some athlete-months while the date-range
1499
+ * read (`fetchCoachAthleteWorkouts`) still works for the same athlete, so an HTTP 500 says so.
1497
1500
  */
1498
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1499
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1501
+ async function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1502
+ const res = await client.request("GET", `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`);
1503
+ const label = `Coach athlete calendar summary for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}`;
1504
+ if (res.ok) {
1505
+ if (Array.isArray(res.data)) return res.data;
1506
+ throw new Error(`${label} returned an unexpected response shape.`);
1507
+ }
1508
+ const message = trainHeroicApiErrorMessage(label, res.status, res.data);
1509
+ if (res.status === 500) throw new CoachMonthSummaryError(`${message.endsWith(".") ? message : `${message}.`} TrainHeroic's month summary fails for some athletes whose date-range workout read still answers; read the same dates through the date-range read.`, res.status);
1510
+ throw new CoachMonthSummaryError(message, res.status);
1500
1511
  }
1501
1512
  /**
1502
1513
  * Resolve a roster athlete's coach-writable calendar program id
@@ -1537,8 +1548,7 @@ async function resolveBuildProgramId(client, args) {
1537
1548
  const [y, m] = parseWorkoutDate(args.date);
1538
1549
  return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1539
1550
  }
1540
- //#endregion
1541
- //#region src/exercise-set-payload.ts
1551
+ // src/exercise-set-payload.ts
1542
1552
  function slotData(exercise, key) {
1543
1553
  const value = exercise?.[key];
1544
1554
  return value === void 0 || value === null ? "" : String(value);
@@ -1606,8 +1616,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1606
1616
  body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
1607
1617
  return body;
1608
1618
  }
1609
- //#endregion
1610
- //#region src/athlete-set-write.ts
1619
+ // src/athlete-set-write.ts
1611
1620
  const WRITE_CONCURRENCY = 4;
1612
1621
  /**
1613
1622
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -2239,8 +2248,7 @@ async function logSessionForAthlete(client, args) {
2239
2248
  sets
2240
2249
  };
2241
2250
  }
2242
- //#endregion
2243
- //#region src/util.ts
2251
+ // src/util.ts
2244
2252
  /**
2245
2253
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2246
2254
  * spread into an object under `exactOptionalPropertyTypes` without the per-key
@@ -2255,8 +2263,7 @@ function definedProps(obj) {
2255
2263
  for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2256
2264
  return result;
2257
2265
  }
2258
- //#endregion
2259
- //#region src/athlete-workout-note.ts
2266
+ // src/athlete-workout-note.ts
2260
2267
  /**
2261
2268
  * PUT /1.0/athlete/savedworkout/{id} — set the athlete's session note (the free-text box on the
2262
2269
  * workout screen) and/or session RPE. The date + programWorkoutId (`athlete_workouts` `id`) locate
@@ -2286,8 +2293,7 @@ async function setAthleteWorkoutNote(client, args) {
2286
2293
  rpe: coerceInt(data.rpe) ?? (args.rpe !== void 0 ? args.rpe : null)
2287
2294
  };
2288
2295
  }
2289
- //#endregion
2290
- //#region src/athlete-exercise-note.ts
2296
+ // src/athlete-exercise-note.ts
2291
2297
  /**
2292
2298
  * PUT /1.0/athlete/savedworkoutsetexercise/{id} — set the athlete's per-exercise note (the
2293
2299
  * "Add exercise note" box on the exercise screen). A notes-only body leaves logged reps/weight
@@ -2308,8 +2314,7 @@ async function setAthleteExerciseNote(client, args) {
2308
2314
  notes: typeof data.notes === "string" ? data.notes : args.notes
2309
2315
  };
2310
2316
  }
2311
- //#endregion
2312
- //#region src/workout-export.ts
2317
+ // src/workout-export.ts
2313
2318
  const DEFAULT_FILENAME_BASE = "trainheroic-workout-history";
2314
2319
  /** Pretty-printed JSON of the structured workouts, exactly as `presentAthleteWorkoutsExport` yields. */
2315
2320
  function workoutsToJson(workouts) {
@@ -2434,8 +2439,7 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
2434
2439
  filename: `${base}.${meta.extension}`
2435
2440
  };
2436
2441
  }
2437
- //#endregion
2438
- //#region src/workout-encode.ts
2442
+ // src/workout-encode.ts
2439
2443
  const LEADERBOARD_TYPE = {
2440
2444
  completion: 0,
2441
2445
  "for completion": 0,
@@ -2609,7 +2613,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2609
2613
  param2Type = ex.param_2_type ?? 1;
2610
2614
  param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2611
2615
  } else {
2612
- param2Type = 0;
2616
+ param2Type = ex.param_2_type ?? 0;
2613
2617
  param2Values = null;
2614
2618
  }
2615
2619
  const entry = {
@@ -2671,9 +2675,6 @@ function buildBlockPayload(blocks, workoutId) {
2671
2675
  };
2672
2676
  });
2673
2677
  }
2674
- function unitOr(t) {
2675
- return unitLabel(t) ?? "?";
2676
- }
2677
2678
  const UNIT_ALIASES = {
2678
2679
  rep: "reps",
2679
2680
  reps: "reps",
@@ -2711,74 +2712,178 @@ function statedUnit(value, label) {
2711
2712
  if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
2712
2713
  return normalized;
2713
2714
  }
2714
- function validateSlotUnit(label, field, stated, paramType, fixedType, allowAddedWeight = false) {
2715
+ /** TrainHeroic param type codes keyed by their unit label (`sec` and `in` each name two). */
2716
+ const TYPES_BY_UNIT = (() => {
2717
+ const map = /* @__PURE__ */ new Map();
2718
+ for (const [code, unit] of Object.entries(PARAM_UNIT)) if (unit !== null) map.set(unit, [...map.get(unit) ?? [], Number(code)]);
2719
+ return map;
2720
+ })();
2721
+ /**
2722
+ * Pick the param type a populated slot is written with. An explicit `param_N_type` wins and
2723
+ * must agree with the stated unit. Otherwise the exercise's library default is kept when it
2724
+ * already has the stated unit, and any other unit maps to its own type code.
2725
+ */
2726
+ function resolveSlotType(label, slot, stated, explicit, libraryDefault) {
2727
+ const field = slot === 1 ? "primaryUnit" : "secondaryUnit";
2715
2728
  if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
2716
2729
  const intended = statedUnit(stated, `${label} / ${field}`);
2717
- const fixed = unitLabel(fixedType);
2718
- if (intended !== fixed && !(allowAddedWeight && (fixedType === 0 || fixedType === null) && intended === "lb")) throw new Error(`${label}: ${field} ${intended} does not match the exercise's fixed ${fixed ?? "unset"} unit. Choose an exercise with the requested unit before building.`);
2719
- if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
2720
- }
2721
- /** Validate both populated slots against the library before any workout write. */
2722
- function validateExerciseUnits(blockTitle, ex, defaults) {
2723
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2724
- if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
2725
- if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
2726
- }
2727
- /** Flag spec params the API will silently override to the exercise's fixed units. */
2728
- function unitAdvisory(blockTitle, ex, defaults) {
2730
+ if (explicit !== void 0) {
2731
+ if (unitLabel(explicit) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param_${slot}_type ${explicit} (${unitLabel(explicit) ?? "unset"}).`);
2732
+ return explicit;
2733
+ }
2734
+ if (libraryDefault !== null && unitLabel(libraryDefault) === intended) return libraryDefault;
2735
+ const [only, ...others] = TYPES_BY_UNIT.get(intended) ?? [];
2736
+ if (only === void 0) throw new Error(`${label}: ${field} ${intended} has no TrainHeroic param type.`);
2737
+ if (others.length === 0) return only;
2738
+ throw new Error(`${label}: ${field} ${intended} matches TrainHeroic param types ${[only, ...others].join(" and ")}; set param_${slot}_type to choose one.`);
2739
+ }
2740
+ /**
2741
+ * Return a copy of `ex` with `param_1_type` and `param_2_type` set to the types the encoder
2742
+ * writes. A slot without values always gets the library default (an explicit type there is
2743
+ * ignored, and `resolveExerciseUnits` warns about it), so only a slot with values can carry a
2744
+ * type that differs from the library.
2745
+ */
2746
+ function withResolvedParamTypes(label, ex, defaults) {
2747
+ const param1 = ex.reps === void 0 ? defaults.param1 ?? 3 : resolveSlotType(label, 1, ex.primaryUnit, ex.param_1_type, defaults.param1);
2748
+ const param2 = ex.weight === void 0 ? defaults.param2 ?? 0 : resolveSlotType(label, 2, ex.secondaryUnit, ex.param_2_type, defaults.param2);
2749
+ return {
2750
+ ...ex,
2751
+ param_1_type: param1,
2752
+ param_2_type: param2
2753
+ };
2754
+ }
2755
+ /**
2756
+ * The slots (1 = primary, 2 = secondary) of a resolved exercise that hold values in a type
2757
+ * other than the library default. This is the one definition of a unit override: the advisory
2758
+ * notes describe these slots, and `buildSession` re-saves a row until TrainHeroic stores
2759
+ * exactly these types.
2760
+ */
2761
+ function overriddenSlots(ex, defaults) {
2762
+ const overridden = [];
2763
+ if (ex.reps !== void 0 && ex.param_1_type !== defaults.param1) overridden.push(1);
2764
+ if (ex.weight !== void 0 && ex.param_2_type !== defaults.param2) overridden.push(2);
2765
+ return overridden;
2766
+ }
2767
+ /** A param type's unit label for advisory text; "unset" for a slot without a type. */
2768
+ function unitName(type) {
2769
+ return unitLabel(type) ?? "unset";
2770
+ }
2771
+ /**
2772
+ * Describe how a resolved exercise's units relate to its library defaults, and flag spec
2773
+ * fields the encoder ignores. `ex` carries the resolved `param_1_type` and `param_2_type`
2774
+ * (from `resolveExerciseUnits`).
2775
+ */
2776
+ function unitAdvisory(label, ex, defaults) {
2729
2777
  const notes = [];
2730
2778
  const warnings = [];
2731
- const u = unitOr;
2732
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2779
+ const u = unitName;
2733
2780
  if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
2734
- const sentP1 = ex.param_1_type;
2735
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2736
- const sp1 = Math.trunc(Number(sentP1));
2737
- warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
2738
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2739
- if (ex.weight !== void 0 && ex.weight !== null) {
2740
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2741
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
2742
- if (sentP2 !== effP2) {
2743
- 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.`);
2744
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2745
- }
2746
- }
2781
+ const overrides = overriddenSlots(ex, defaults);
2782
+ if (overrides.includes(1)) notes.push(`${label}: primary values are in ${u(ex.param_1_type)}, set on this session in place of the exercise's default ${u(defaults.param1)}.`);
2783
+ else if (ex.reps !== void 0 && ex.param_1_type !== 3) notes.push(`${label}: values are in ${u(ex.param_1_type)} (the exercise's default primary unit).`);
2784
+ const addedLoad = ex.param_2_type === 1 && (defaults.param2 === 0 || defaults.param2 === null);
2785
+ if (overrides.includes(2) && !addedLoad) notes.push(`${label}: secondary values are in ${u(ex.param_2_type)}, set on this session in place of the exercise's default ${u(defaults.param2)}.`);
2747
2786
  return {
2748
2787
  notes,
2749
2788
  warnings
2750
2789
  };
2751
2790
  }
2791
+ /** Warn about explicit param types on slots without values, which the encoder ignores. */
2792
+ function ignoredTypeWarnings(label, ex) {
2793
+ const warnings = [];
2794
+ if (ex.reps === void 0 && ex.param_1_type !== void 0) warnings.push(`${label}: param_1_type ${ex.param_1_type} is ignored because reps has no values; the slot keeps the exercise's default.`);
2795
+ if (ex.weight === void 0 && ex.param_2_type !== void 0) warnings.push(`${label}: param_2_type ${ex.param_2_type} is ignored because weight has no values; the slot keeps the exercise's default.`);
2796
+ return warnings;
2797
+ }
2752
2798
  /**
2753
- * Validate every populated value's stated unit against current TrainHeroic exercise data,
2754
- * then collect non-blocking advisories. The write path calls this before creating a workout;
2755
- * TrainHeroic silently replaces mismatched types.
2799
+ * Resolve every exercise's param types against current TrainHeroic exercise data and collect
2800
+ * non-blocking advisories. Throws, before anything is written, when a populated slot has no
2801
+ * stated unit, an unknown unit, or a unit that disagrees with an explicit param type. The
2802
+ * returned blocks carry the resolved `param_1_type` and `param_2_type` on every exercise.
2756
2803
  */
2757
- async function collectAdvisories(blocks, index) {
2758
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2759
- block: b,
2760
- ex
2761
- })));
2762
- const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
2804
+ async function resolveExerciseUnits(blocks, index) {
2805
+ const ids = [...new Set(blocks.flatMap((b) => b.exercises.map((ex) => Number(ex.id))).filter(Number.isFinite))];
2763
2806
  const defaultsById = await index.currentDefaultsMany(ids);
2764
2807
  const notes = [];
2765
2808
  const warnings = [];
2766
- pairs.forEach((p) => {
2767
- const def = defaultsById.get(Number(p.ex.id));
2768
- if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
2769
- validateExerciseUnits(p.block.title, p.ex, def);
2770
- const advisory = unitAdvisory(p.block.title, p.ex, def);
2771
- notes.push(...advisory.notes);
2772
- warnings.push(...advisory.warnings);
2773
- });
2774
2809
  return {
2775
- notes,
2776
- warnings
2810
+ blocks: blocks.map((block) => ({
2811
+ ...block,
2812
+ exercises: block.exercises.map((ex) => {
2813
+ const label = `${block.title} / ${ex.title ?? ex.id}`;
2814
+ const def = defaultsById.get(Number(ex.id));
2815
+ if (!def) throw new Error(`${label}: exercise id ${ex.id} was not found in the library.`);
2816
+ const typed = withResolvedParamTypes(label, ex, def);
2817
+ const advisory = unitAdvisory(label, typed, def);
2818
+ notes.push(...advisory.notes);
2819
+ warnings.push(...ignoredTypeWarnings(label, ex), ...advisory.warnings);
2820
+ return typed;
2821
+ })
2822
+ })),
2823
+ defaultsById,
2824
+ advisories: {
2825
+ notes,
2826
+ warnings
2827
+ }
2777
2828
  };
2778
2829
  }
2779
- //#endregion
2780
- //#region src/workout-session.ts
2830
+ /**
2831
+ * Validate units and collect advisories without writing a workout. This is the preview entry
2832
+ * point; `resolveExerciseUnits` also returns the resolved blocks that `buildSession` writes.
2833
+ */
2834
+ async function collectAdvisories(blocks, index) {
2835
+ return (await resolveExerciseUnits(blocks, index)).advisories;
2836
+ }
2837
+ // src/workout-session.ts
2781
2838
  const EXERCISE_SAVE_CONCURRENCY = 4;
2839
+ const SAVE_EXERCISES_PATH = "/2.0/coach/calendar/saveWorkoutSetExercises";
2840
+ /**
2841
+ * Pair each sent entry with the row TrainHeroic returned for it. A block's rows are matched on
2842
+ * `order` (unique within one block's payload) and must carry the same `exercise_id` and an id.
2843
+ * Throws when the response is not a row array or a row is missing, because the caller cannot
2844
+ * then confirm which units TrainHeroic stored.
2845
+ */
2846
+ function matchSavedRows(saves, response, pwId) {
2847
+ if (!Array.isArray(response)) throw new Error(`saveWorkoutSetExercises returned an unexpected response shape for draft session ${pwId}.`);
2848
+ const rows = response.filter((row) => typeof row === "object" && row !== null);
2849
+ return saves.map((save) => {
2850
+ const row = rows.find((r) => coerceInt(r.order) === coerceInt(save.entry.order) && coerceInt(r.exercise_id) === coerceInt(save.entry.exercise_id));
2851
+ const id = coerceInt(row?.id);
2852
+ if (row === void 0 || id === null) throw new Error(`saveWorkoutSetExercises returned no row for exercise ${String(save.entry.exercise_id)} (order ${String(save.entry.order)}) on draft session ${pwId}.`);
2853
+ return {
2854
+ save,
2855
+ row,
2856
+ id
2857
+ };
2858
+ });
2859
+ }
2860
+ /** True when the stored row holds the requested type in every overridden slot. */
2861
+ function keepsOverrides(save, row) {
2862
+ return save.overrides.every((slot) => coerceInt(row[`param_${slot}_type`]) === coerceInt(save.entry[`param_${slot}_type`]));
2863
+ }
2864
+ /**
2865
+ * Save one block's exercises. TrainHeroic stores a newly inserted row with the exercise's
2866
+ * library param types whatever the request says, and keeps the requested types when the same
2867
+ * row is saved again with its `id`; the coach web app's unit picker saves single rows by id
2868
+ * the same way. So each row with an overridden slot (say %max load on a pounds lift) that the
2869
+ * insert stored in the library type is saved a second time by id. Throws when the second save
2870
+ * still does not hold the requested types, because the values would render in the wrong unit.
2871
+ */
2872
+ async function saveBlockExercises(client, pwId, saves) {
2873
+ const corrections = matchSavedRows(saves, await req(client, "POST", SAVE_EXERCISES_PATH, saves.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row)).map(({ save, id }) => ({
2874
+ entry: {
2875
+ ...save.entry,
2876
+ id
2877
+ },
2878
+ overrides: save.overrides
2879
+ }));
2880
+ if (corrections.length === 0) return;
2881
+ const unkept = matchSavedRows(corrections, await req(client, "POST", SAVE_EXERCISES_PATH, corrections.map((save) => save.entry)), pwId).filter(({ save, row }) => !keepsOverrides(save, row));
2882
+ if (unkept.length > 0) {
2883
+ const names = unkept.map(({ save, row }) => typeof row.title === "string" && row.title !== "" ? row.title : `exercise ${String(save.entry.exercise_id)}`).join(", ");
2884
+ throw new Error(`TrainHeroic did not keep the requested units for ${names} on draft session ${pwId}. Remove the draft or correct those exercises in the coach app.`);
2885
+ }
2886
+ }
2782
2887
  /**
2783
2888
  * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2784
2889
  * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
@@ -2807,8 +2912,9 @@ async function buildSession(client, opts) {
2807
2912
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
2808
2913
  const splitSummary = setSplitSummary(validatedBlocks);
2809
2914
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
2810
- const advisories = await collectAdvisories(validatedBlocks, opts.index);
2811
- const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
2915
+ const resolved = await resolveExerciseUnits(validatedBlocks, opts.index);
2916
+ const advisories = resolved.advisories;
2917
+ const blocks = splitSummary === null ? resolved.blocks : splitOversizedBlocks(resolved.blocks);
2812
2918
  const sess = await req(client, "POST", createPath(opts), {});
2813
2919
  checkResponse(sessionCreateResponseSchema, sess, "session create");
2814
2920
  const workoutId = Number(sess.workout_id);
@@ -2821,9 +2927,13 @@ async function buildSession(client, opts) {
2821
2927
  if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2822
2928
  return block.exercises.map((ex, j) => {
2823
2929
  counter += 1;
2824
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2930
+ const defaults = resolved.defaultsById.get(Number(ex.id));
2931
+ return {
2932
+ entry: makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`),
2933
+ overrides: defaults === void 0 ? [] : overriddenSlots(ex, defaults)
2934
+ };
2825
2935
  });
2826
- }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (payload) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", payload));
2936
+ }).filter((p) => p.length > 0), EXERCISE_SAVE_CONCURRENCY, (saves) => saveBlockExercises(client, pwId, saves));
2827
2937
  if (opts.instruction !== void 0 && opts.instruction !== "") {
2828
2938
  const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2829
2939
  await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
@@ -2872,6 +2982,7 @@ async function readSession(client, programId, date, pwId) {
2872
2982
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2873
2983
  return {
2874
2984
  pwId,
2985
+ workoutId: coerceInt(pw.workout_id),
2875
2986
  date: `${str$1(pw.year)}-${str$1(pw.month).padStart(2, "0")}-${str$1(pw.day).padStart(2, "0")}`,
2876
2987
  published: pw.published,
2877
2988
  instruction: str$1(pw.instruction),
@@ -2909,8 +3020,7 @@ function readExercise(ex) {
2909
3020
  instruction: str$1(ex.instruction)
2910
3021
  };
2911
3022
  }
2912
- //#endregion
2913
- //#region src/coach.ts
3023
+ // src/coach.ts
2914
3024
  const DEFAULT_INVITE_MESSAGE = "Follow these steps and you'll be set up and ready to go!";
2915
3025
  const PROGRAM_KINDS = ["calendar", "fixed"];
2916
3026
  /**
@@ -3296,9 +3406,26 @@ async function requestAnalytics(client, args) {
3296
3406
  body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
3297
3407
  }
3298
3408
  const res = await client.request("POST", spec.path, { body });
3299
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3409
+ if (!res.ok) {
3410
+ const message = trainHeroicApiErrorMessage(`Analytics ${args.metric}`, res.status, res.data);
3411
+ throw new Error(withHint(message, analyticsErrorHint(res.data)));
3412
+ }
3300
3413
  return res.data;
3301
3414
  }
3415
+ /**
3416
+ * Explain TrainHeroic's terse analytics rejections so the caller can fix its input.
3417
+ * lift-1rm-history answers "Invalid exercise id" for any exercise that is not a weighted lift
3418
+ * (verified with Run, Push-Up, and an unknown id; Back Squat succeeds).
3419
+ */
3420
+ function analyticsErrorHint(responseBody) {
3421
+ if (typeof responseBody === "string" && responseBody.includes("Invalid exercise id")) return "exerciseId must be a weighted lift such as Back Squat (id 1); bodyweight, distance, and unknown exercises are rejected.";
3422
+ return null;
3423
+ }
3424
+ /** Append a sentence of guidance to an error message that may or may not end in a period. */
3425
+ function withHint(message, hint) {
3426
+ if (hint === null) return message;
3427
+ return `${message.endsWith(".") ? message : `${message}.`} ${hint}`;
3428
+ }
3302
3429
  function reportRows(report) {
3303
3430
  if (report === null || typeof report !== "object") return null;
3304
3431
  const rows = report.rows;
@@ -3438,10 +3565,31 @@ async function createSessionTemplate(client, args) {
3438
3565
  if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template create response is missing an id.");
3439
3566
  return res.data;
3440
3567
  }
3568
+ /**
3569
+ * Copy an existing calendar session, with its blocks and exercises, into the coach's session
3570
+ * library as a new template
3571
+ * (`POST /2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/{workoutId}`). The path takes
3572
+ * the session's workout id and the body's `id` takes its programWorkout id (pwId), which is what
3573
+ * the coach web app sends. TrainHeroic answers HTTP 500 when the body is missing, when the body
3574
+ * has no `id`, or when the two ids are swapped.
3575
+ */
3576
+ async function saveSessionAsTemplate(client, args) {
3577
+ const title = args.title.trim();
3578
+ if (title === "") throw new Error("Session template title must not be blank.");
3579
+ const res = await client.request("POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${args.workoutId}`, { body: {
3580
+ id: args.pwId,
3581
+ title
3582
+ } });
3583
+ if (!res.ok) {
3584
+ const message = trainHeroicApiErrorMessage(`Saving session ${args.pwId} (workout ${args.workoutId}) as a template`, res.status, res.data);
3585
+ throw new Error(withHint(message, "Check that workoutId and pwId belong to the same session; a session read-back returns both."));
3586
+ }
3587
+ if (!isRecord(res.data) || coerceInt(res.data.id) === null) throw new Error("Session template save response is missing an id.");
3588
+ return res.data;
3589
+ }
3441
3590
  /** First page of the coach session-template library (`GET /1.0/coach/workouts`). */
3442
3591
  const SESSION_TEMPLATES_LIST_PATH = "/1.0/coach/workouts?page=1&pageSize=50";
3443
- //#endregion
3444
- //#region src/main-lifts.ts
3592
+ // src/main-lifts.ts
3445
3593
  /**
3446
3594
  * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
3447
3595
  * first family that matches, so the more specific / easily-confused families come before the broad
@@ -3653,8 +3801,7 @@ async function fetchRosterMainLiftPRs(client, opts = {}) {
3653
3801
  };
3654
3802
  });
3655
3803
  }
3656
- //#endregion
3657
- //#region src/messaging.ts
3804
+ // src/messaging.ts
3658
3805
  const BUCKETS = [
3659
3806
  ["team", "teams"],
3660
3807
  ["athlete", "athletes"],
@@ -3709,8 +3856,7 @@ async function readLive(client, streamId, limit, afterCommentId) {
3709
3856
  if (afterCommentId !== void 0) return limit !== void 0 && limit > 0 ? res.data.slice(0, limit) : res.data;
3710
3857
  return limit !== void 0 && limit > 0 ? res.data.slice(-limit) : res.data;
3711
3858
  }
3712
- //#endregion
3713
- //#region src/library-cache.ts
3859
+ // src/library-cache.ts
3714
3860
  /** In-memory cache (no persistence). The default when none is supplied. */
3715
3861
  var MemoryLibraryCache = class {
3716
3862
  #snapshot = null;
@@ -3721,8 +3867,7 @@ var MemoryLibraryCache = class {
3721
3867
  this.#snapshot = snapshot;
3722
3868
  }
3723
3869
  };
3724
- //#endregion
3725
- //#region src/exercise-index.ts
3870
+ // src/exercise-index.ts
3726
3871
  const LIBRARY_PATH = "/v5/exerciseLibrary/all";
3727
3872
  const CREATE_PATH = "/2.0/coach/exercise/create";
3728
3873
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
@@ -3928,5 +4073,4 @@ var ExerciseLibrary = class {
3928
4073
  };
3929
4074
  }
3930
4075
  };
3931
- //#endregion
3932
- export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, TrainHeroicUnavailableError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchCurrentExerciseDefaults, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, isTrainHeroicUnavailableStatus, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, trainHeroicApiErrorMessage, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
4076
+ export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, CoachMonthSummaryError, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, TrainHeroicUnavailableError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchCurrentExerciseDefaults, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, isTrainHeroicUnavailableStatus, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, overriddenSlots, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveExerciseUnits, resolveLeaderboard, saveSessionAsTemplate, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, trainHeroicApiErrorMessage, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
@@ -1,4 +1,3 @@
1
- //#region src/library-cache.d.ts
2
1
  /** A persisted snapshot of the exercise library: the raw rows plus when they were fetched. */
3
2
  type LibrarySnapshot = {
4
3
  fetchedAt: number;
@@ -18,5 +17,4 @@ declare class MemoryLibraryCache implements LibraryCache {
18
17
  load(): Promise<LibrarySnapshot | null>;
19
18
  save(snapshot: LibrarySnapshot): Promise<void>;
20
19
  }
21
- //#endregion
22
20
  export { LibrarySnapshot as n, MemoryLibraryCache as r, LibraryCache as t };
package/dist/node.d.mts CHANGED
@@ -1,5 +1,4 @@
1
- import { n as LibrarySnapshot, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
- //#region src/node.d.ts
1
+ import { n as LibrarySnapshot, t as LibraryCache } from "./library-cache-TkOsfh5m.mjs";
3
2
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
4
3
  export declare function defaultCachePath(): string;
5
4
  /** Persists the exercise library to a JSON file. */
@@ -8,5 +7,4 @@ export declare class JsonFileLibraryCache implements LibraryCache {
8
7
  constructor(path?: string);
9
8
  load(): Promise<LibrarySnapshot | null>;
10
9
  save(snapshot: LibrarySnapshot): Promise<void>;
11
- }
12
- //#endregion
10
+ }
package/dist/node.mjs CHANGED
@@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import process from "node:process";
5
- //#region src/node.ts
5
+ // src/node.ts
6
6
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
7
7
  function defaultCachePath() {
8
8
  return process.env.TRAINHEROIC_CACHE_FILE ?? join(homedir(), ".trainheroic", "library.json");
@@ -25,5 +25,4 @@ var JsonFileLibraryCache = class {
25
25
  await writeFile(this.#path, JSON.stringify(snapshot), { mode: 384 });
26
26
  }
27
27
  };
28
- //#endregion
29
28
  export { JsonFileLibraryCache, defaultCachePath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "4.2.0",
3
+ "version": "4.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,14 +26,14 @@
26
26
  "dist"
27
27
  ],
28
28
  "dependencies": {
29
- "es-toolkit": "^1.52.0",
30
- "zod": "^4.6.5",
31
- "@trainheroic-unofficial/dto": "4.2.0"
29
+ "es-toolkit": "^1.53.2",
30
+ "zod": "^4.6.7",
31
+ "@trainheroic-unofficial/dto": "4.3.0"
32
32
  },
33
33
  "devDependencies": {
34
- "@types/node": "^26.6.4",
35
- "tsdown": "^0.23.0",
36
- "vitest": "^5.0.3"
34
+ "@types/node": "^26.6.6",
35
+ "tsdown": "^0.23.7",
36
+ "vitest": "^5.1.0"
37
37
  },
38
38
  "scripts": {
39
39
  "build": "tsdown",