@trainheroic-unofficial/js 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -110,6 +110,21 @@ const client = new TrainHeroicClient(
110
110
  If the reused token has expired, the next request gets a 401/403; the client logs in once with
111
111
  the credentials, retries, and updates `client.sessionId` to the new token.
112
112
 
113
+ The optional fourth constructor argument can persist renewed sessions and report final HTTP
114
+ failures without coupling the SDK to a telemetry vendor:
115
+
116
+ ```ts
117
+ const client = new TrainHeroicClient(email, password, savedSession, {
118
+ onSession: saveSession,
119
+ onHttpError: (error) => telemetry.captureException(error),
120
+ });
121
+ ```
122
+
123
+ `onHttpError` receives a `TrainHeroicHttpError` containing only the method, status, and host.
124
+ Paths, query strings, bodies, credentials, and session tokens are excluded. A transient 401/403
125
+ that succeeds after automatic re-login does not call the hook, and synchronous or asynchronous
126
+ hook failures never change the request result.
127
+
113
128
  ## Two entry points
114
129
 
115
130
  ```ts
package/dist/index.d.mts CHANGED
@@ -2,6 +2,21 @@ import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from
2
2
  import { Advisory, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
3
3
  import { ZodType } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
+ //#region src/http-error.d.ts
6
+ /**
7
+ * A final non-2xx response from TrainHeroic. The error deliberately carries only request
8
+ * metadata that is safe to send to telemetry: never the path, query string, request body,
9
+ * response body, credentials, or session token.
10
+ */
11
+ declare class TrainHeroicHttpError extends Error {
12
+ readonly name = "TrainHeroicHttpError";
13
+ readonly method: string;
14
+ readonly status: number;
15
+ readonly host: string;
16
+ constructor(method: string, url: string, status: number);
17
+ }
18
+ type TrainHeroicHttpErrorHandler = (error: TrainHeroicHttpError) => void | PromiseLike<void>;
19
+ //#endregion
5
20
  //#region src/auth.d.ts
6
21
  type TrainHeroicSession = {
7
22
  thUserId: number;
@@ -9,13 +24,17 @@ type TrainHeroicSession = {
9
24
  scope: string;
10
25
  role: string;
11
26
  };
27
+ type LoginOptions = {
28
+ /** Called for every non-2xx login response; callback failures never change the result. */
29
+ onHttpError?: TrainHeroicHttpErrorHandler;
30
+ };
12
31
  /**
13
32
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
14
33
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
15
34
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
16
35
  * is sent as the `session-token` header and works against both API hosts.
17
36
  */
18
- declare function loginTrainHeroic(email: string, password: string): Promise<TrainHeroicSession | null>;
37
+ declare function loginTrainHeroic(email: string, password: string, options?: LoginOptions): Promise<TrainHeroicSession | null>;
19
38
  //#endregion
20
39
  //#region src/client.d.ts
21
40
  declare class TrainHeroicAuthError extends Error {
@@ -39,6 +58,12 @@ type ClientOptions = {
39
58
  * instead of logging in again.
40
59
  */
41
60
  onSession?: (sessionId: string) => void;
61
+ /**
62
+ * Called once when a login or API request finishes with a non-2xx response. Transient 401/403
63
+ * API responses that succeed after the built-in re-login are not reported. The callback is
64
+ * best-effort: telemetry failures never change the API result returned to the caller.
65
+ */
66
+ onHttpError?: TrainHeroicHttpErrorHandler;
42
67
  };
43
68
  /**
44
69
  * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
@@ -956,4 +981,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
956
981
  stats(): Promise<Record<string, unknown>>;
957
982
  }
958
983
  //#endregion
959
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
984
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, LoginOptions, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/dist/index.mjs CHANGED
@@ -1,6 +1,34 @@
1
1
  import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  import { z } from "zod";
3
3
  export * from "@trainheroic-unofficial/dto";
4
+ //#region src/http-error.ts
5
+ /**
6
+ * A final non-2xx response from TrainHeroic. The error deliberately carries only request
7
+ * metadata that is safe to send to telemetry: never the path, query string, request body,
8
+ * response body, credentials, or session token.
9
+ */
10
+ var TrainHeroicHttpError = class extends Error {
11
+ name = "TrainHeroicHttpError";
12
+ method;
13
+ status;
14
+ host;
15
+ constructor(method, url, status) {
16
+ const parsed = new URL(url);
17
+ const normalizedMethod = method.toUpperCase();
18
+ super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
19
+ this.method = normalizedMethod;
20
+ this.status = status;
21
+ this.host = parsed.host;
22
+ }
23
+ };
24
+ /** Call observability hooks without allowing them to change SDK behavior. */
25
+ function notifyHttpError(handler, method, url, status) {
26
+ if (!handler) return;
27
+ try {
28
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
29
+ } catch {}
30
+ }
31
+ //#endregion
4
32
  //#region src/auth.ts
5
33
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
6
34
  /**
@@ -22,8 +50,9 @@ function authUrl() {
22
50
  * the Phase 0 spike: no refresh_token, no api_token, no TTL). The 48-char session_id
23
51
  * is sent as the `session-token` header and works against both API hosts.
24
52
  */
25
- async function loginTrainHeroic(email, password) {
26
- const res = await fetch(authUrl(), {
53
+ async function loginTrainHeroic(email, password, options = {}) {
54
+ const url = authUrl();
55
+ const res = await fetch(url, {
27
56
  method: "POST",
28
57
  headers: {
29
58
  "content-type": "application/x-www-form-urlencoded",
@@ -34,7 +63,10 @@ async function loginTrainHeroic(email, password) {
34
63
  password
35
64
  }).toString()
36
65
  });
37
- if (!res.ok) return null;
66
+ if (!res.ok) {
67
+ notifyHttpError(options.onHttpError, "POST", url, res.status);
68
+ return null;
69
+ }
38
70
  const data = await res.json().catch(() => null);
39
71
  if (!data || typeof data.id !== "number" || !data.session_id) return null;
40
72
  return {
@@ -77,6 +109,7 @@ var TrainHeroicClient = class {
77
109
  #email;
78
110
  #password;
79
111
  #onSession;
112
+ #onHttpError;
80
113
  #sessionId;
81
114
  #loginInFlight = null;
82
115
  constructor(email, password, sessionId = null, options = {}) {
@@ -84,6 +117,7 @@ var TrainHeroicClient = class {
84
117
  this.#password = password;
85
118
  this.#sessionId = sessionId;
86
119
  this.#onSession = options.onSession;
120
+ this.#onHttpError = options.onHttpError;
87
121
  }
88
122
  get sessionId() {
89
123
  return this.#sessionId;
@@ -98,7 +132,7 @@ var TrainHeroicClient = class {
98
132
  }
99
133
  }
100
134
  async #login() {
101
- const session = await loginTrainHeroic(this.#email, this.#password);
135
+ const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
102
136
  if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
103
137
  this.#sessionId = session.sessionId;
104
138
  try {
@@ -115,6 +149,7 @@ var TrainHeroicClient = class {
115
149
  session = await this.#ensureSession();
116
150
  res = await this.#send(method, url, session, options.body);
117
151
  }
152
+ if (!res.ok) notifyHttpError(this.#onHttpError, method, url, res.status);
118
153
  const text = await res.text();
119
154
  let data = text;
120
155
  if (text.length > 0) try {
@@ -2006,8 +2041,10 @@ function unitAdvisory(blockTitle, ex, defaults) {
2006
2041
  if (ex.weight !== void 0 && ex.weight !== null) {
2007
2042
  const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2008
2043
  const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2009
- if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2010
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2044
+ if (sentP2 !== effP2) {
2045
+ if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2046
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2047
+ }
2011
2048
  }
2012
2049
  return {
2013
2050
  notes,
@@ -2979,4 +3016,4 @@ var ExerciseLibrary = class {
2979
3016
  }
2980
3017
  };
2981
3018
  //#endregion
2982
- export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
3019
+ export { ANALYTICS_METRIC_KEYS, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, MAX_PARAM_SLOTS, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, dateWindows, defaultBlockType, definedProps, deleteComment, exerciseTitle, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,10 +27,10 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "2.1.0"
30
+ "@trainheroic-unofficial/dto": "2.1.1"
31
31
  },
32
32
  "devDependencies": {
33
- "@types/node": "^26.1.2",
33
+ "@types/node": "^26.2.0",
34
34
  "tsdown": "^0.22.14",
35
35
  "vitest": "^4.1.10"
36
36
  },