@trainheroic-unofficial/js 3.5.2 → 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
@@ -4,17 +4,30 @@ import { chunk } from "es-toolkit/array";
4
4
  import { ZodType } from "zod";
5
5
  export * from "@trainheroic-unofficial/dto";
6
6
  //#region src/http-error.d.ts
7
- /**
8
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
9
- * metadata that is safe to send to telemetry: never the path, query string, request body,
10
- * response body, credentials, or session token.
11
- */
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. */
12
23
  declare class TrainHeroicHttpError extends Error {
13
24
  readonly name = "TrainHeroicHttpError";
14
25
  readonly method: string;
15
26
  readonly status: number;
16
27
  readonly host: string;
17
- 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);
18
31
  }
19
32
  type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
20
33
  //#endregion
@@ -1165,4 +1178,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
1165
1178
  stats(): Promise<Record<string, unknown>>;
1166
1179
  }
1167
1180
  //#endregion
1168
- 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, 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, 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 };
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
@@ -3,30 +3,200 @@ import { chunk, uniq } from "es-toolkit/array";
3
3
  import { z } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
5
  //#region src/http-error.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
- */
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. */
11
177
  var TrainHeroicHttpError = class extends Error {
12
178
  name = "TrainHeroicHttpError";
13
179
  method;
14
180
  status;
15
181
  host;
16
- constructor(method, url, status) {
182
+ requestBody;
183
+ responseBody;
184
+ constructor(method, url, status, diagnostics = {}) {
17
185
  const parsed = new URL(url);
18
186
  const normalizedMethod = method.toUpperCase();
19
187
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
20
188
  this.method = normalizedMethod;
21
189
  this.status = status;
22
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);
23
193
  }
24
194
  };
25
195
  /** Call observability hooks without allowing them to change SDK behavior. */
26
- function notifyHttpError(handler, method, url, status) {
196
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
27
197
  if (!handler) return;
28
198
  try {
29
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
199
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
30
200
  } catch {}
31
201
  }
32
202
  //#endregion
@@ -150,14 +320,19 @@ var TrainHeroicClient = class {
150
320
  session = await this.#ensureSession();
151
321
  res = await this.#send(method, url, session, options.body);
152
322
  }
153
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
154
- const text = await res.text();
155
- let data = text;
156
- if (text.length > 0) try {
157
- data = JSON.parse(text);
158
- } catch {
159
- 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;
160
330
  }
331
+ const data = parseResponseText(text);
332
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
333
+ requestBody: options.body,
334
+ responseBody: data
335
+ });
161
336
  return {
162
337
  status: res.status,
163
338
  ok: res.ok,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "3.5.2",
3
+ "version": "3.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,7 +28,7 @@
28
28
  "dependencies": {
29
29
  "es-toolkit": "^1.52.0",
30
30
  "zod": "^4.4.3",
31
- "@trainheroic-unofficial/dto": "3.5.2"
31
+ "@trainheroic-unofficial/dto": "3.6.0"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/node": "^26.3.0",