@trainheroic-unofficial/js 1.3.0 → 1.4.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/dist/index.d.mts CHANGED
@@ -189,7 +189,11 @@ declare function presentAthleteWorkouts(list: readonly ProgramWorkout[]): Athlet
189
189
  /** The minimal id scaffold `log-set` / `logForAthlete` needs for one saved workout set. */
190
190
  type LogSetTarget = {
191
191
  date: string;
192
- workoutTitle: string; /** The id for `--set` (logAthleteSet/logForAthlete `savedWorkoutSetId`). */
192
+ workoutTitle: string; /** The program this saved workout belongs to — lets a caller pick the right one of several. */
193
+ program: string | null;
194
+ programId: number | null;
195
+ team: string | null;
196
+ teamId: number | null; /** The id for `--set` (logAthleteSet/logForAthlete `savedWorkoutSetId`). */
193
197
  savedWorkoutSetId: number;
194
198
  setTitle: string | null;
195
199
  exercises: Array<{
@@ -200,13 +204,27 @@ type LogSetTarget = {
200
204
  performed: string[];
201
205
  }>;
202
206
  };
207
+ /**
208
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
209
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
210
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
211
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
212
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
213
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
214
+ */
215
+ declare function selectWorkoutsByProgram(list: readonly ProgramWorkout[], filter: {
216
+ programId?: number;
217
+ teamId?: number;
218
+ programTitle?: string;
219
+ }): ProgramWorkout[];
203
220
  /**
204
221
  * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
205
222
  * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
206
223
  * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
207
224
  * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
208
- * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
209
- * with no resolvable id.
225
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
226
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
227
+ * dropping any set with no resolvable id.
210
228
  */
211
229
  declare function presentLogTargets(list: readonly ProgramWorkout[]): LogSetTarget[];
212
230
  /**
@@ -757,4 +775,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
757
775
  stats(): Promise<Record<string, unknown>>;
758
776
  }
759
777
  //#endregion
760
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
778
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BuildOptions, ClientResult, CoachRosterAthlete, DEFAULT_INVITE_MESSAGE, ExerciseIndex, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, LogSessionResult, LogSetTarget, MAIN_LIFT_FAMILIES, MainLiftFamily, MainLiftFamilyKey, MainLiftPR, MainLiftResolution, MemoryLibraryCache, PARAM_NONE, PARAM_PCT_MAX, PARAM_REPS, PARAM_RPE, PARAM_UNIT, PARAM_WEIGHT, PersonalWorkoutCreated, RequestOptions, ResolvedLift, SessionExercise, SetResult, SetWriteMode, SwapExerciseResult, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicSession, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/dist/index.mjs CHANGED
@@ -1,7 +1,20 @@
1
1
  import { exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
2
  export * from "@trainheroic-unofficial/dto";
3
3
  //#region src/auth.ts
4
- const AUTH_URL = "https://apis.trainheroic.com/auth";
4
+ const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
5
+ /**
6
+ * The login endpoint, allowing an env override so a test harness can authenticate against a local
7
+ * fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
8
+ * the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
9
+ * (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
10
+ */
11
+ function authUrl() {
12
+ const env = globalThis.process?.env;
13
+ if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
14
+ const apis = env?.TH_APIS_BASE;
15
+ if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
16
+ return DEFAULT_AUTH_URL;
17
+ }
5
18
  /**
6
19
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
7
20
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
@@ -9,7 +22,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
9
22
  * is sent as the `session-token` header and works against both API hosts.
10
23
  */
11
24
  async function loginTrainHeroic(email, password) {
12
- const res = await fetch(AUTH_URL, {
25
+ const res = await fetch(authUrl(), {
13
26
  method: "POST",
14
27
  headers: {
15
28
  "content-type": "application/x-www-form-urlencoded",
@@ -32,8 +45,19 @@ async function loginTrainHeroic(email, password) {
32
45
  }
33
46
  //#endregion
34
47
  //#region src/client.ts
35
- const COACH_BASE = "https://api.trainheroic.com";
36
- const APIS_BASE = "https://apis.trainheroic.com";
48
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
49
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
50
+ /**
51
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
52
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
53
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
54
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
55
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
56
+ */
57
+ function envBase(key, fallback) {
58
+ const v = (globalThis.process?.env)?.[key];
59
+ return v && v.length > 0 ? v : fallback;
60
+ }
37
61
  var TrainHeroicAuthError = class extends Error {
38
62
  name = "TrainHeroicAuthError";
39
63
  };
@@ -72,7 +96,7 @@ var TrainHeroicClient = class {
72
96
  return this.#sessionId;
73
97
  }
74
98
  async request(method, path, options = {}) {
75
- const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
99
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
76
100
  let session = await this.#ensureSession();
77
101
  let res = await this.#send(method, url, session, options.body);
78
102
  if (res.status === 401 || res.status === 403) {
@@ -596,12 +620,35 @@ function presentAthleteWorkouts(list) {
596
620
  return list.map(presentAthleteWorkout);
597
621
  }
598
622
  /**
623
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
624
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
625
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
626
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
627
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
628
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
629
+ */
630
+ function selectWorkoutsByProgram(list, filter) {
631
+ const { programId, teamId, programTitle } = filter;
632
+ const needle = programTitle?.trim().toLowerCase();
633
+ if (programId === void 0 && teamId === void 0 && !needle) return [...list];
634
+ return list.filter((pw) => {
635
+ const rec = pw;
636
+ if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
637
+ if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
638
+ if (needle) {
639
+ if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
640
+ }
641
+ return false;
642
+ });
643
+ }
644
+ /**
599
645
  * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
600
646
  * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
601
647
  * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
602
648
  * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
603
- * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
604
- * with no resolvable id.
649
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
650
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
651
+ * dropping any set with no resolvable id.
605
652
  */
606
653
  function presentLogTargets(list) {
607
654
  const targets = [];
@@ -612,6 +659,10 @@ function presentLogTargets(list) {
612
659
  if (!saved) continue;
613
660
  const date = str$1(rec.date) ?? "";
614
661
  const workoutTitle = str$1(rec.workout_title) ?? "";
662
+ const program = str$1(rec.program_title);
663
+ const programId = coerceInt(rec.program_id);
664
+ const team = str$1(rec.team_title);
665
+ const teamId = coerceInt(rec.team_id);
615
666
  const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
616
667
  for (const s of sets) {
617
668
  if (!isRecord(s)) continue;
@@ -631,6 +682,10 @@ function presentLogTargets(list) {
631
682
  targets.push({
632
683
  date,
633
684
  workoutTitle,
685
+ program,
686
+ programId,
687
+ team,
688
+ teamId,
634
689
  savedWorkoutSetId,
635
690
  setTitle: str$1(s.title),
636
691
  exercises
@@ -992,7 +1047,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
992
1047
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
993
1048
  }
994
1049
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
995
- if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1050
+ 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.`);
996
1051
  const body = {
997
1052
  ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
998
1053
  ...extra
@@ -2376,4 +2431,4 @@ var ExerciseLibrary = class {
2376
2431
  }
2377
2432
  };
2378
2433
  //#endregion
2379
- export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, 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, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
2434
+ export { ANALYTICS_METRIC_KEYS, DEFAULT_INVITE_MESSAGE, ExerciseLibrary, LEADERBOARD_LABEL, LEADERBOARD_TYPE, MAIN_LIFT_FAMILIES, 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, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, definedProps, deleteComment, exerciseUnits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteUser, fetchAthleteWorkouts, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkouts, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, publishSession, queryAnalytics, rankSearch, readLive, readSession, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveLeaderboard, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, setSessionInstruction, sortRosterByRecency, summarizeAthleteWorkouts, swapAthleteExercise, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, withUnits };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "1.3.0"
30
+ "@trainheroic-unofficial/dto": "1.4.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",