@trainheroic-unofficial/js 3.5.1 → 3.6.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
@@ -120,8 +120,13 @@ const client = new TrainHeroicClient(email, password, savedSession, {
120
120
  });
121
121
  ```
122
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
123
+ `onHttpError` receives a `TrainHeroicHttpError` containing the method, status, host, a bounded
124
+ request-body summary, and sanitized provider response diagnostics. The request summary records
125
+ field names plus a small allowlist of non-sensitive enum values; arbitrary request values are
126
+ never included. Response diagnostics retain bounded status fields and boolean success flags while
127
+ redacting all free-form strings and omitting unknown fields. Paths, query strings, credentials,
128
+ session tokens, and login
129
+ request and response data remain excluded. A transient 401/403
125
130
  that succeeds after automatic re-login does not call the hook, and synchronous or asynchronous
126
131
  hook failures never change the request result.
127
132
 
package/dist/index.d.mts CHANGED
@@ -1,19 +1,33 @@
1
1
  import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
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";
3
+ import { chunk } from "es-toolkit/array";
3
4
  import { ZodType } from "zod";
4
5
  export * from "@trainheroic-unofficial/dto";
5
6
  //#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
- */
7
+ type JsonScalar = boolean | number | string | null;
8
+ type RequestBodySummary = {
9
+ type: "array";
10
+ length: number;
11
+ } | {
12
+ type: "object";
13
+ keys: string[];
14
+ values?: Record<string, JsonScalar>;
15
+ } | {
16
+ type: "boolean" | "number" | "other" | "string";
17
+ };
18
+ type TrainHeroicHttpErrorDiagnostics = {
19
+ requestBody?: unknown;
20
+ responseBody?: unknown;
21
+ };
22
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
11
23
  declare class TrainHeroicHttpError extends Error {
12
24
  readonly name = "TrainHeroicHttpError";
13
25
  readonly method: string;
14
26
  readonly status: number;
15
27
  readonly host: string;
16
- constructor(method: string, url: string, status: number);
28
+ readonly requestBody: RequestBodySummary | undefined;
29
+ readonly responseBody: unknown;
30
+ constructor(method: string, url: string, status: number, diagnostics?: TrainHeroicHttpErrorDiagnostics);
17
31
  }
18
32
  type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
19
33
  //#endregion
@@ -160,13 +174,27 @@ declare function rankSearch<T extends {
160
174
  title: string;
161
175
  can_edit?: number;
162
176
  }>(rows: readonly T[], query: string, limit: number): T[];
163
- declare function chunk<T>(items: readonly T[], size: number): T[][];
164
177
  /**
165
178
  * Map over items with a bounded number of concurrent workers. Used to fan out upstream
166
179
  * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
167
180
  * on workerd, blowing the subrequest budget.
168
181
  */
169
182
  declare function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
183
+ /**
184
+ * A concurrency limiter shared across independent call sites: at most `max` tasks run at once,
185
+ * the rest wait in FIFO order. Where {@link mapPool} bounds one fan-out, a limiter bounds the sum
186
+ * of several nested ones (a session write that fans out per set, each of which fans out per
187
+ * exercise) to a single ceiling. `cancel` stops the queue: tasks not yet started, and any run
188
+ * after it, reject with the given error, while tasks already running finish normally, so one
189
+ * failed write halts the rest of a session without abandoning requests already on the wire.
190
+ */
191
+ type Limiter = {
192
+ run<T>(task: () => Promise<T>): Promise<T>;
193
+ /** Run required finalization even after cancellation, while preserving the same concurrency cap. */
194
+ runFinalizer<T>(task: () => Promise<T>): Promise<T>;
195
+ cancel(error: unknown): void;
196
+ };
197
+ declare function createLimiter(max: number): Limiter;
170
198
  /**
171
199
  * The exercise-library surface the tools depend on, so the tools work over either a
172
200
  * D1-backed mirror (hosted, multi-tenant) or an in-memory cache (local, single-user).
@@ -221,7 +249,12 @@ declare function fetchExerciseHistoryList(client: TrainHeroicClient): Promise<Ex
221
249
  declare function fetchRecentExercises(client: TrainHeroicClient): Promise<unknown[]>;
222
250
  declare function fetchAthleteCircuits(client: TrainHeroicClient, kind?: "recent" | "history"): Promise<unknown[]>;
223
251
  declare function fetchAthleteProgrammingPrograms(client: TrainHeroicClient): Promise<unknown[]>;
224
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
252
+ /**
253
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
254
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
255
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
256
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
257
+ */
225
258
  declare function searchExerciseHistory(client: TrainHeroicClient, query: string, limit?: number): Promise<ExerciseHistoryListItem[]>;
226
259
  declare function fetchExerciseHistoryDetail(client: TrainHeroicClient, exerciseId: number, userId: number): Promise<ExerciseHistoryDetail>;
227
260
  declare function fetchPersonalRecords(client: TrainHeroicClient, exerciseId: number): Promise<PersonalRecord[]>;
@@ -262,6 +295,16 @@ declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number,
262
295
  pageSize?: number;
263
296
  gender?: number;
264
297
  }): Promise<unknown>;
298
+ /**
299
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
300
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
301
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
302
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
303
+ */
304
+ declare function performedExercises(workouts: readonly ProgramWorkout[]): Array<{
305
+ exerciseId: number;
306
+ title: string;
307
+ }>;
265
308
  /**
266
309
  * Flatten one range item into a readable workout: each exercise carries its `prescribed` and
267
310
  * `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
@@ -350,6 +393,16 @@ declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId:
350
393
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
351
394
  declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
352
395
  //#endregion
396
+ //#region src/exercise-history.d.ts
397
+ /**
398
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
399
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
400
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
401
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
402
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
403
+ */
404
+ declare function historyInRange(presented: PresentedExerciseHistory, since: string | undefined, until: string | undefined): PresentedExerciseHistory;
405
+ //#endregion
353
406
  //#region src/coach-athlete-calendar.d.ts
354
407
  /**
355
408
  * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
@@ -1125,4 +1178,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
1125
1178
  stats(): Promise<Record<string, unknown>>;
1126
1179
  }
1127
1180
  //#endregion
1128
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, DEFAULT_INVITE_MESSAGE, DeletedProgram, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, RequestOptions, ResolvedLift, SESSION_TEMPLATES_LIST_PATH, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, SetSplit, type SetWriteMode, SwapExerciseResult, TeamPublishTarget, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, 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, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
1181
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, DEFAULT_INVITE_MESSAGE, DeletedProgram, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, Limiter, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, type RequestBodySummary, RequestOptions, ResolvedLift, SESSION_TEMPLATES_LIST_PATH, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, SetSplit, type SetWriteMode, SwapExerciseResult, TeamPublishTarget, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorDiagnostics, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, 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, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, 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, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/dist/index.mjs CHANGED
@@ -1,31 +1,202 @@
1
1
  import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programCreateResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
+ import { chunk, uniq } from "es-toolkit/array";
2
3
  import { z } from "zod";
3
4
  export * from "@trainheroic-unofficial/dto";
4
5
  //#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
- */
6
+ const MAX_REQUEST_KEYS = 50;
7
+ const MAX_RESPONSE_DEPTH = 4;
8
+ const MAX_RESPONSE_KEYS = 20;
9
+ const MAX_RESPONSE_ITEMS = 10;
10
+ const MAX_RESPONSE_NODES = 50;
11
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
12
+ "code",
13
+ "detail",
14
+ "details",
15
+ "error",
16
+ "error_code",
17
+ "errors",
18
+ "message",
19
+ "reason",
20
+ "status",
21
+ "status_code",
22
+ "success"
23
+ ]);
24
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
25
+ "data",
26
+ "received",
27
+ "response",
28
+ "result"
29
+ ]);
30
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
31
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
32
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
33
+ 0,
34
+ 1,
35
+ 2,
36
+ 3,
37
+ 4,
38
+ 5,
39
+ 6,
40
+ 7,
41
+ 10,
42
+ 11,
43
+ 12,
44
+ 13,
45
+ 14,
46
+ 18
47
+ ]);
48
+ function safeFieldName(key) {
49
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
50
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
51
+ return key;
52
+ }
53
+ function boundedEntries(object, limit) {
54
+ const entries = [];
55
+ for (const key of Object.keys(object)) {
56
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
57
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
58
+ if (entries.length >= limit) break;
59
+ }
60
+ return entries;
61
+ }
62
+ function safeRequestValue(key, value) {
63
+ if (key === "is_circuit" && typeof value === "boolean") return value;
64
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
65
+ }
66
+ function requestBodySummary(body) {
67
+ if (Array.isArray(body)) return {
68
+ type: "array",
69
+ length: body.length
70
+ };
71
+ if (body && typeof body === "object") {
72
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
73
+ const keys = entries.map(([key]) => safeFieldName(key));
74
+ const values = {};
75
+ for (const [key, value] of entries) {
76
+ const safeValue = safeRequestValue(key, value);
77
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
78
+ }
79
+ return Object.keys(values).length > 0 ? {
80
+ type: "object",
81
+ keys,
82
+ values
83
+ } : {
84
+ type: "object",
85
+ keys
86
+ };
87
+ }
88
+ const primitive = typeof body;
89
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
90
+ }
91
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
92
+ if (budget.nodes <= 0) return "[Truncated]";
93
+ budget.nodes -= 1;
94
+ if (value === null) return null;
95
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
96
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
97
+ if (typeof value === "string") return "[Redacted]";
98
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
99
+ if (Array.isArray(value)) {
100
+ const result = [];
101
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
102
+ if (budget.nodes <= 0) {
103
+ result.push("[Truncated]");
104
+ break;
105
+ }
106
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
107
+ }
108
+ return result;
109
+ }
110
+ if (value && typeof value === "object") {
111
+ const result = {};
112
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
113
+ if (budget.nodes <= 0) {
114
+ result.truncated = "[Truncated]";
115
+ break;
116
+ }
117
+ const safeKey = safeFieldName(key);
118
+ const safeValue = safeRequestValue(key, item);
119
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
120
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
121
+ else if (safeValue !== void 0) {
122
+ budget.nodes -= 1;
123
+ result[safeKey] = safeValue;
124
+ }
125
+ }
126
+ return result;
127
+ }
128
+ return `[${typeof value}]`;
129
+ }
130
+ function responseBodyDiagnostics(body, budget, depth = 0) {
131
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
132
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
133
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
134
+ const object = body;
135
+ const result = {};
136
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
137
+ if (activeBudget.nodes <= 0) {
138
+ result.truncated = "[Truncated]";
139
+ break;
140
+ }
141
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
142
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
143
+ continue;
144
+ }
145
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
146
+ activeBudget.nodes -= 1;
147
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
148
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
149
+ }
150
+ }
151
+ if (Object.keys(result).length > 0) return result;
152
+ return { type: "object" };
153
+ }
154
+ function parseResponseText(text) {
155
+ if (text.length === 0) return text;
156
+ try {
157
+ return JSON.parse(text);
158
+ } catch {
159
+ return text;
160
+ }
161
+ }
162
+ function safeRequestBodySummary(body) {
163
+ try {
164
+ return requestBodySummary(body);
165
+ } catch {
166
+ return { type: "other" };
167
+ }
168
+ }
169
+ function safeResponseBodyDiagnostics(body) {
170
+ try {
171
+ return responseBodyDiagnostics(body);
172
+ } catch {
173
+ return "[Unavailable]";
174
+ }
175
+ }
176
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
10
177
  var TrainHeroicHttpError = class extends Error {
11
178
  name = "TrainHeroicHttpError";
12
179
  method;
13
180
  status;
14
181
  host;
15
- constructor(method, url, status) {
182
+ requestBody;
183
+ responseBody;
184
+ constructor(method, url, status, diagnostics = {}) {
16
185
  const parsed = new URL(url);
17
186
  const normalizedMethod = method.toUpperCase();
18
187
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
19
188
  this.method = normalizedMethod;
20
189
  this.status = status;
21
190
  this.host = parsed.host;
191
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
192
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
22
193
  }
23
194
  };
24
195
  /** Call observability hooks without allowing them to change SDK behavior. */
25
- function notifyHttpError(handler, method, url, status) {
196
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
26
197
  if (!handler) return;
27
198
  try {
28
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
199
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
29
200
  } catch {}
30
201
  }
31
202
  //#endregion
@@ -149,14 +320,19 @@ var TrainHeroicClient = class {
149
320
  session = await this.#ensureSession();
150
321
  res = await this.#send(method, url, session, options.body);
151
322
  }
152
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
153
- const text = await res.text();
154
- let data = text;
155
- if (text.length > 0) try {
156
- data = JSON.parse(text);
157
- } catch {
158
- data = text;
323
+ const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
324
+ let text;
325
+ try {
326
+ text = await res.text();
327
+ } catch (error) {
328
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
329
+ throw error;
159
330
  }
331
+ const data = parseResponseText(text);
332
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
333
+ requestBody: options.body,
334
+ responseBody: data
335
+ });
160
336
  return {
161
337
  status: res.status,
162
338
  ok: res.ok,
@@ -370,29 +546,82 @@ function rankSearch(rows, query, limit) {
370
546
  };
371
547
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
372
548
  }
373
- function chunk(items, size) {
374
- const out = [];
375
- for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
376
- return out;
377
- }
378
549
  /**
379
550
  * Map over items with a bounded number of concurrent workers. Used to fan out upstream
380
551
  * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
381
552
  * on workerd, blowing the subrequest budget.
382
553
  */
383
554
  async function mapPool(items, limit, fn) {
555
+ assertPositiveInteger(limit, "Concurrency limit");
384
556
  const out = Array.from({ length: items.length });
385
557
  let next = 0;
558
+ const state = { failure: null };
386
559
  const worker = async () => {
387
- while (next < items.length) {
560
+ while (next < items.length && state.failure === null) {
388
561
  const i = next;
389
562
  next += 1;
390
- out[i] = await fn(items[i], i);
563
+ try {
564
+ out[i] = await fn(items[i], i);
565
+ } catch (error) {
566
+ state.failure ??= { error };
567
+ }
391
568
  }
392
569
  };
393
570
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
571
+ if (state.failure !== null) throw state.failure.error;
394
572
  return out;
395
573
  }
574
+ function createLimiter(max) {
575
+ assertPositiveInteger(max, "Maximum concurrency");
576
+ let active = 0;
577
+ let cancelled = null;
578
+ const waiting = [];
579
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
580
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
581
+ else if (active < max) {
582
+ active += 1;
583
+ resolve();
584
+ } else waiting.push({
585
+ start: () => {
586
+ active += 1;
587
+ resolve();
588
+ },
589
+ abort: reject,
590
+ finalizer
591
+ });
592
+ });
593
+ const release = () => {
594
+ active -= 1;
595
+ waiting.shift()?.start();
596
+ };
597
+ return {
598
+ async run(task) {
599
+ await acquire(false);
600
+ try {
601
+ return await task();
602
+ } finally {
603
+ release();
604
+ }
605
+ },
606
+ async runFinalizer(task) {
607
+ await acquire(true);
608
+ try {
609
+ return await task();
610
+ } finally {
611
+ release();
612
+ }
613
+ },
614
+ cancel(error) {
615
+ cancelled ??= { error };
616
+ const queued = waiting.splice(0);
617
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
618
+ else entry.abort(error);
619
+ }
620
+ };
621
+ }
622
+ function assertPositiveInteger(value, label) {
623
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
624
+ }
396
625
  //#endregion
397
626
  //#region src/athlete.ts
398
627
  async function getJson(client, path, label) {
@@ -446,39 +675,25 @@ function sortRosterByRecency(rows) {
446
675
  * summary becomes a null-data row (sorted last), not an error.
447
676
  */
448
677
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
449
- const rows = [];
450
- const concurrency = 6;
451
- const uniqueAthleteIds = [...new Set(athleteIds)];
452
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
453
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
454
- const settled = await Promise.all(chunk.map(async (id) => {
455
- try {
456
- return {
457
- id,
458
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
459
- };
460
- } catch {
461
- return {
462
- id,
463
- summary: null
464
- };
465
- }
466
- }));
467
- for (const { id, summary } of settled) {
468
- const count = summary?.sessions_count ?? null;
469
- const hasSessions = count !== null && count > 0;
470
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
471
- rows.push({
472
- athleteId: id,
473
- sessionsCount: count,
474
- firstLoggedDate: normDate(summary?.first_logged_date),
475
- lastLoggedDate: normDate(summary?.last_logged_date),
476
- totalReps: summary?.reps_sum ?? null,
477
- totalVolume: summary?.volume_sum ?? null
478
- });
678
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
679
+ let summary;
680
+ try {
681
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
682
+ } catch {
683
+ summary = null;
479
684
  }
480
- }
481
- return sortRosterByRecency(rows);
685
+ const count = summary?.sessions_count ?? null;
686
+ const hasSessions = count !== null && count > 0;
687
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
688
+ return {
689
+ athleteId: id,
690
+ sessionsCount: count,
691
+ firstLoggedDate: normDate(summary?.first_logged_date),
692
+ lastLoggedDate: normDate(summary?.last_logged_date),
693
+ totalReps: summary?.reps_sum ?? null,
694
+ totalVolume: summary?.volume_sum ?? null
695
+ };
696
+ }));
482
697
  }
483
698
  function fetchAthletePrefs(client) {
484
699
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
@@ -498,9 +713,19 @@ function fetchAthleteCircuits(client, kind = "recent") {
498
713
  function fetchAthleteProgrammingPrograms(client) {
499
714
  return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
500
715
  }
501
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
716
+ /**
717
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
718
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
719
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
720
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
721
+ */
502
722
  async function searchExerciseHistory(client, query, limit = 20) {
503
- return rankSearch(await fetchExerciseHistoryList(client), query, limit);
723
+ const tokens = buildSearchText(query).split(/\s+/u).filter((t) => t.length > 0);
724
+ if (tokens.length === 0) return [];
725
+ return rankSearch((await fetchExerciseHistoryList(client)).filter((row) => {
726
+ const text = buildSearchText(row.title);
727
+ return tokens.every((t) => text.includes(t));
728
+ }), query, limit);
504
729
  }
505
730
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
506
731
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -615,6 +840,28 @@ function slotValues(ex, requireMade) {
615
840
  }
616
841
  return map;
617
842
  }
843
+ /**
844
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
845
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
846
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
847
+ * only prescription, since personal work has no template tree at all.
848
+ */
849
+ function unmadeSlotValues(ex) {
850
+ const map = slotValues(ex, false);
851
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
852
+ return map;
853
+ }
854
+ /**
855
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
856
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
857
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
858
+ * slots are the whole prescription.
859
+ */
860
+ function prescriptionSlots(template, saved) {
861
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
862
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
863
+ return map;
864
+ }
618
865
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
619
866
  function fmtSlot(slot) {
620
867
  const has1 = slot.p1 !== null;
@@ -624,10 +871,6 @@ function fmtSlot(slot) {
624
871
  if (has2) return `@ ${slot.p2}`;
625
872
  return "";
626
873
  }
627
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
628
- function prescribedStrings(ex) {
629
- return [...slotValues(ex, false).values()].map(fmtSlot);
630
- }
631
874
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
632
875
  function performedStrings(ex) {
633
876
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -649,6 +892,46 @@ function savedSets(saved) {
649
892
  return out;
650
893
  }
651
894
  /**
895
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
896
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
897
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
898
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
899
+ */
900
+ function performedExercises(workouts) {
901
+ const out = [];
902
+ for (const pw of workouts) {
903
+ const rec = pw;
904
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
905
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
906
+ const templates = /* @__PURE__ */ new Map();
907
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
908
+ if (!isRecord(set)) continue;
909
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
910
+ for (const ex of exercises) {
911
+ if (!isRecord(ex)) continue;
912
+ const id = coerceInt(ex.id);
913
+ if (id !== null) templates.set(id, {
914
+ exerciseId: coerceInt(ex.exercise_id),
915
+ title: exerciseTitle(ex)
916
+ });
917
+ }
918
+ }
919
+ const saved = savedWorkoutOf(pw);
920
+ if (!saved) continue;
921
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
922
+ const templateId = coerceInt(ex.workout_set_exercise_id);
923
+ const template = templateId === null ? void 0 : templates.get(templateId);
924
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
925
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
926
+ out.push({
927
+ exerciseId,
928
+ title: exerciseTitle(ex, template?.title)
929
+ });
930
+ }
931
+ }
932
+ return out;
933
+ }
934
+ /**
652
935
  * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
653
936
  * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
654
937
  * entered values live in the same `param_N_data` slots as a prescription.
@@ -663,6 +946,15 @@ function performedSlotsByExerciseId(sets) {
663
946
  }
664
947
  return map;
665
948
  }
949
+ /** Each saved-copy row keyed by the prescription exercise id it was copied from. */
950
+ function savedRowsByTemplateId(sets) {
951
+ const map = /* @__PURE__ */ new Map();
952
+ for (const { exercises } of sets) for (const ex of exercises) {
953
+ const id = coerceInt(ex.workout_set_exercise_id);
954
+ if (id !== null && !map.has(id)) map.set(id, ex);
955
+ }
956
+ return map;
957
+ }
666
958
  /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
667
959
  function notesByTemplateId(sets) {
668
960
  const map = /* @__PURE__ */ new Map();
@@ -686,7 +978,7 @@ function mergeExercise(prescribed, performed, meta) {
686
978
  };
687
979
  }
688
980
  /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
689
- function mergePrescriptionBlock(set, performedById, notesById) {
981
+ function mergePrescriptionBlock(set, performedById, savedById, notesById) {
690
982
  const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
691
983
  return {
692
984
  order: coerceInt(set.order) ?? 0,
@@ -696,7 +988,7 @@ function mergePrescriptionBlock(set, performedById, notesById) {
696
988
  exercises: exercises.filter(isRecord).map((ex) => {
697
989
  const id = coerceInt(ex.id);
698
990
  const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
699
- return mergeExercise(slotValues(ex, false), performed, {
991
+ return mergeExercise(prescriptionSlots(ex, id !== null ? savedById.get(id) : void 0), performed, {
700
992
  exerciseId: coerceInt(ex.exercise_id),
701
993
  title: typeof ex.title === "string" ? ex.title : "",
702
994
  instruction: str(ex.instruction),
@@ -706,14 +998,18 @@ function mergePrescriptionBlock(set, performedById, notesById) {
706
998
  })
707
999
  };
708
1000
  }
709
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
1001
+ /**
1002
+ * A block straight from the saved copy (athlete-added or personal work; no template row). Its
1003
+ * unperformed slots are the prescription — a personal session's targets live only here — and its
1004
+ * performed slots are what was logged.
1005
+ */
710
1006
  function mergeSavedBlock(set, exercises) {
711
1007
  return {
712
1008
  order: coerceInt(set.order) ?? 0,
713
1009
  title: str(set.title),
714
1010
  instruction: str(set.instruction),
715
1011
  isTest: coerceInt(set.is_test) === 1,
716
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
1012
+ exercises: exercises.map((ex) => mergeExercise(prescriptionSlots(void 0, ex), slotValues(ex, true), {
717
1013
  exerciseId: coerceInt(ex.exercise_id),
718
1014
  title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
719
1015
  instruction: str(ex.instruction),
@@ -736,8 +1032,9 @@ function mergeAthleteWorkout(raw) {
736
1032
  const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
737
1033
  const logged = savedSets(saved);
738
1034
  const performedById = performedSlotsByExerciseId(logged);
1035
+ const savedById = savedRowsByTemplateId(logged);
739
1036
  const notesById = notesByTemplateId(logged);
740
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
1037
+ const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, savedById, notesById)).sort((a, b) => a.order - b.order);
741
1038
  const prescribedIds = /* @__PURE__ */ new Set();
742
1039
  for (const s of prescriptionSets) {
743
1040
  const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
@@ -749,7 +1046,7 @@ function mergeAthleteWorkout(raw) {
749
1046
  }
750
1047
  for (const { set, exercises } of logged) {
751
1048
  const extra = exercises.filter((ex) => {
752
- if (slotValues(ex, true).size === 0) return false;
1049
+ if (slotValues(ex, false).size === 0) return false;
753
1050
  const id = coerceInt(ex.workout_set_exercise_id);
754
1051
  return id === null || !prescribedIds.has(id);
755
1052
  });
@@ -925,6 +1222,16 @@ function presentLogTargets(list) {
925
1222
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
926
1223
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
927
1224
  if (!saved) continue;
1225
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1226
+ const templatesById = /* @__PURE__ */ new Map();
1227
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1228
+ if (!isRecord(tSet)) continue;
1229
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
1230
+ for (const tEx of tExs) {
1231
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
1232
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
1233
+ }
1234
+ }
928
1235
  const date = str(rec.date) ?? "";
929
1236
  const workoutTitle = str(rec.workout_title) ?? "";
930
1237
  const program = str(rec.program_title);
@@ -939,12 +1246,14 @@ function presentLogTargets(list) {
939
1246
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
940
1247
  const id = coerceInt(ex.id);
941
1248
  if (id === null) return null;
1249
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1250
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
942
1251
  return {
943
1252
  savedWorkoutSetExerciseId: id,
944
1253
  title: exerciseTitle(ex),
945
1254
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
946
1255
  notes: str(ex.notes),
947
- prescribed: prescribedStrings(ex),
1256
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
948
1257
  performed: performedStrings(ex)
949
1258
  };
950
1259
  }).filter((e) => e !== null);
@@ -1069,6 +1378,28 @@ function presentExerciseHistory(detail) {
1069
1378
  };
1070
1379
  }
1071
1380
  //#endregion
1381
+ //#region src/exercise-history.ts
1382
+ /**
1383
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1384
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
1385
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
1386
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
1387
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
1388
+ */
1389
+ function historyInRange(presented, since, until) {
1390
+ if (since === void 0 && until === void 0) return presented;
1391
+ const sessions = presented.sessions.filter((s) => {
1392
+ const d = (s.date ?? "").slice(0, 10);
1393
+ if (since !== void 0 && d < since) return false;
1394
+ if (until !== void 0 && d > until) return false;
1395
+ return true;
1396
+ });
1397
+ return {
1398
+ ...presented,
1399
+ sessions
1400
+ };
1401
+ }
1402
+ //#endregion
1072
1403
  //#region src/coach-athlete-calendar.ts
1073
1404
  async function getArray(client, path, label) {
1074
1405
  const res = await client.request("GET", path);
@@ -1203,6 +1534,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1203
1534
  }
1204
1535
  //#endregion
1205
1536
  //#region src/athlete-set-write.ts
1537
+ const WRITE_CONCURRENCY = 4;
1206
1538
  /**
1207
1539
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1208
1540
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1444,6 +1776,41 @@ async function swapAthleteExercise(client, args) {
1444
1776
  originalTeamExerciseId: coerceInt(template.exercise_id)
1445
1777
  };
1446
1778
  }
1779
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
1780
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1781
+ assertUniqueExerciseResults(results);
1782
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1783
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1784
+ return {
1785
+ savedWorkoutSetId,
1786
+ exercises,
1787
+ rawSet,
1788
+ suffix,
1789
+ extra,
1790
+ writes: results.map((result) => {
1791
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
1792
+ if (!ex) {
1793
+ const valid = exercises.map((candidate) => {
1794
+ const id = coerceInt(candidate.id);
1795
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
1796
+ }).filter((label) => label !== null);
1797
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1798
+ }
1799
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1800
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
1801
+ return {
1802
+ id: result.savedWorkoutSetExerciseId,
1803
+ body: {
1804
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1805
+ ...extra
1806
+ }
1807
+ };
1808
+ })
1809
+ };
1810
+ }
1811
+ function errorMessage(error) {
1812
+ return error instanceof Error ? error.message : String(error);
1813
+ }
1447
1814
  /**
1448
1815
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
1449
1816
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -1457,36 +1824,40 @@ async function swapAthleteExercise(client, args) {
1457
1824
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
1458
1825
  * open.
1459
1826
  */
1460
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1461
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1462
- assertUniqueExerciseResults(results);
1463
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1464
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1465
- let exercisesWritten = 0;
1466
- const projectedCompletion = /* @__PURE__ */ new Map();
1467
- for (const result of results) {
1468
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1469
- if (!ex) {
1470
- const valid = exercises.map((e) => {
1471
- const id = coerceInt(e.id);
1472
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
1473
- }).filter((x) => x !== null);
1474
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1475
- }
1476
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1477
- if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
1478
- const body = {
1479
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1480
- ...extra
1827
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
1828
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
1829
+ const put = (path, body, failureMessage, finalizer = false) => {
1830
+ const request = async () => {
1831
+ try {
1832
+ const res = await client.request("PUT", path, { body });
1833
+ if (!res.ok) throw new Error(failureMessage(res.status));
1834
+ } catch (error) {
1835
+ limit.cancel(error);
1836
+ throw error;
1837
+ }
1481
1838
  };
1482
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1483
- if (!res.ok) {
1484
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
1485
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1486
- }
1487
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
1488
- exercisesWritten += 1;
1839
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
1840
+ };
1841
+ const confirmed = [];
1842
+ try {
1843
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
1844
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
1845
+ return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
1846
+ });
1847
+ confirmed.push(id);
1848
+ if (sessionProgress) {
1849
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
1850
+ sessionConfirmed.push(id);
1851
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
1852
+ }
1853
+ });
1854
+ } catch (error) {
1855
+ if (sessionProgress || confirmed.length === 0) throw error;
1856
+ confirmed.sort((a, b) => a - b);
1857
+ throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
1489
1858
  }
1859
+ const exercisesWritten = writes.length;
1860
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
1490
1861
  let setCompleted = false;
1491
1862
  if (mode === "log") {
1492
1863
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -1494,8 +1865,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1494
1865
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1495
1866
  ...extra
1496
1867
  };
1497
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1498
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1868
+ try {
1869
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
1870
+ } catch (error) {
1871
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
1872
+ }
1499
1873
  setCompleted = true;
1500
1874
  }
1501
1875
  }
@@ -1505,6 +1879,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1505
1879
  setCompleted
1506
1880
  };
1507
1881
  }
1882
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
1883
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
1884
+ }
1508
1885
  /**
1509
1886
  * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
1510
1887
  * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
@@ -1677,7 +2054,7 @@ function prescribedExerciseLabels(workouts) {
1677
2054
  return labels;
1678
2055
  }
1679
2056
  /** Group resolved exercises by saved set and write each set via the given log target. */
1680
- async function logResolvedExercises(client, target, workouts, resolved) {
2057
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
1681
2058
  const bySet = /* @__PURE__ */ new Map();
1682
2059
  for (const r of resolved) {
1683
2060
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1687,15 +2064,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
1687
2064
  });
1688
2065
  bySet.set(r.savedWorkoutSetId, list);
1689
2066
  }
1690
- const out = [];
1691
- for (const [savedWorkoutSetId, results] of bySet) {
1692
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
1693
- out.push({
1694
- savedWorkoutSetId: written.savedWorkoutSetId,
1695
- exercisesLogged: written.exercisesWritten
2067
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
2068
+ const limit = createLimiter(WRITE_CONCURRENCY);
2069
+ const confirmedBySet = /* @__PURE__ */ new Map();
2070
+ const succeeded = [];
2071
+ try {
2072
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
2073
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
2074
+ succeeded.push(written.savedWorkoutSetId);
2075
+ return {
2076
+ savedWorkoutSetId: written.savedWorkoutSetId,
2077
+ exercisesLogged: written.exercisesWritten
2078
+ };
1696
2079
  });
2080
+ } catch (error) {
2081
+ const completed = new Set(succeeded);
2082
+ const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
2083
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
2084
+ succeeded.sort((a, b) => a - b);
2085
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
2086
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
2087
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
1697
2088
  }
1698
- return out;
1699
2089
  }
1700
2090
  /**
1701
2091
  * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
@@ -1768,7 +2158,7 @@ async function logSessionForAthlete(client, args) {
1768
2158
  const sets = await logResolvedExercises(client, {
1769
2159
  role: "coach",
1770
2160
  athleteId: args.athleteId
1771
- }, day, resolved);
2161
+ }, day, resolved, "Retry the same request to reconcile them.");
1772
2162
  return {
1773
2163
  date: args.date,
1774
2164
  created: false,
@@ -2357,7 +2747,7 @@ async function readSession(client, programId, date, pwId) {
2357
2747
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2358
2748
  return {
2359
2749
  pwId,
2360
- date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
2750
+ date: `${str$1(pw.year)}-${str$1(pw.month).padStart(2, "0")}-${str$1(pw.day).padStart(2, "0")}`,
2361
2751
  published: pw.published,
2362
2752
  instruction: str$1(pw.instruction),
2363
2753
  blocks
@@ -2377,14 +2767,13 @@ function readBlock(b) {
2377
2767
  };
2378
2768
  }
2379
2769
  function readExercise(ex) {
2380
- const reps = [];
2381
- const load = [];
2382
- for (let i = 1; i <= 10; i += 1) {
2383
- const r = str$1(ex[`param_1_data_${i}`]);
2384
- if (r !== "") reps.push(r);
2385
- const w = str$1(ex[`param_2_data_${i}`]);
2386
- if (w !== "") load.push(w);
2387
- }
2770
+ let last = 0;
2771
+ for (let i = 1; i <= 10; i += 1) if (str$1(ex[`param_1_data_${i}`]) !== "" || str$1(ex[`param_2_data_${i}`]) !== "") last = i;
2772
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
2773
+ const repsRaw = slots.map((i) => str$1(ex[`param_1_data_${i}`]));
2774
+ const loadRaw = slots.map((i) => str$1(ex[`param_2_data_${i}`]));
2775
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
2776
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
2388
2777
  return {
2389
2778
  order: Number(ex.order),
2390
2779
  title: str$1(ex.title),
@@ -2961,8 +3350,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2961
3350
  } catch {
2962
3351
  workouts = [];
2963
3352
  }
2964
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2965
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
3353
+ for (const ex of performedExercises(workouts)) {
2966
3354
  const family = classifyMainLift(ex.title);
2967
3355
  if (family === null) continue;
2968
3356
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3207,6 +3595,7 @@ var ExerciseLibrary = class {
3207
3595
  #byId = /* @__PURE__ */ new Map();
3208
3596
  #loaded = false;
3209
3597
  #fetchedAt = 0;
3598
+ #loading = null;
3210
3599
  constructor(client, cache = new MemoryLibraryCache()) {
3211
3600
  this.#client = client;
3212
3601
  this.#cache = cache;
@@ -3234,8 +3623,11 @@ var ExerciseLibrary = class {
3234
3623
  });
3235
3624
  }
3236
3625
  async ensureFresh() {
3237
- if (!this.#loaded) await this.#ensureLoaded();
3238
- else if (Date.now() - this.#fetchedAt > TTL_MS) await this.refresh();
3626
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS) return;
3627
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
3628
+ this.#loading = null;
3629
+ });
3630
+ await this.#loading;
3239
3631
  }
3240
3632
  async refresh() {
3241
3633
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -3254,6 +3646,7 @@ var ExerciseLibrary = class {
3254
3646
  return presentExercise(s.raw);
3255
3647
  }
3256
3648
  async defaultsMany(ids) {
3649
+ await this.ensureFresh();
3257
3650
  const result = /* @__PURE__ */ new Map();
3258
3651
  for (const id of ids) {
3259
3652
  const s = this.#byId.get(id);
@@ -3341,4 +3734,4 @@ var ExerciseLibrary = class {
3341
3734
  }
3342
3735
  };
3343
3736
  //#endregion
3344
- export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, 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, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
3737
+ export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, 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, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,8 +26,9 @@
26
26
  "dist"
27
27
  ],
28
28
  "dependencies": {
29
+ "es-toolkit": "^1.52.0",
29
30
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "3.5.1"
31
+ "@trainheroic-unofficial/dto": "3.6.0"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@types/node": "^26.3.0",