@trainheroic-unofficial/cli 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.
Files changed (2) hide show
  1. package/dist/cli.mjs +74 -11
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -319,7 +319,20 @@ function parseWorkoutDate(s) {
319
319
  }
320
320
  //#endregion
321
321
  //#region ../js/src/auth.ts
322
- const AUTH_URL = "https://apis.trainheroic.com/auth";
322
+ const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
323
+ /**
324
+ * The login endpoint, allowing an env override so a test harness can authenticate against a local
325
+ * fake backend. Precedence: an explicit `TH_AUTH_URL`, else `${TH_APIS_BASE}/auth` (login lives on
326
+ * the apis host, so it follows that base), else the real endpoint. Read via `globalThis.process`
327
+ * (no `import process`) to keep this module workerd-safe, and per call so a child-env override wins.
328
+ */
329
+ function authUrl() {
330
+ const env = globalThis.process?.env;
331
+ if (env?.TH_AUTH_URL && env.TH_AUTH_URL.length > 0) return env.TH_AUTH_URL;
332
+ const apis = env?.TH_APIS_BASE;
333
+ if (apis && apis.length > 0) return `${apis.replace(/\/$/, "")}/auth`;
334
+ return DEFAULT_AUTH_URL;
335
+ }
323
336
  /**
324
337
  * Authenticate against TrainHeroic. Returns the session bundle, or null on bad
325
338
  * credentials. TrainHeroic returns only { id, scope, role, session_id } (verified in
@@ -327,7 +340,7 @@ const AUTH_URL = "https://apis.trainheroic.com/auth";
327
340
  * is sent as the `session-token` header and works against both API hosts.
328
341
  */
329
342
  async function loginTrainHeroic(email, password) {
330
- const res = await fetch(AUTH_URL, {
343
+ const res = await fetch(authUrl(), {
331
344
  method: "POST",
332
345
  headers: {
333
346
  "content-type": "application/x-www-form-urlencoded",
@@ -350,8 +363,19 @@ async function loginTrainHeroic(email, password) {
350
363
  }
351
364
  //#endregion
352
365
  //#region ../js/src/client.ts
353
- const COACH_BASE = "https://api.trainheroic.com";
354
- const APIS_BASE = "https://apis.trainheroic.com";
366
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
367
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
368
+ /**
369
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
370
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
371
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
372
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
373
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
374
+ */
375
+ function envBase(key, fallback) {
376
+ const v = (globalThis.process?.env)?.[key];
377
+ return v && v.length > 0 ? v : fallback;
378
+ }
355
379
  var TrainHeroicAuthError = class extends Error {
356
380
  name = "TrainHeroicAuthError";
357
381
  };
@@ -390,7 +414,7 @@ var TrainHeroicClient = class {
390
414
  return this.#sessionId;
391
415
  }
392
416
  async request(method, path, options = {}) {
393
- const url = `${options.base === "apis" ? APIS_BASE : COACH_BASE}/${path.replace(/^\//, "")}`;
417
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
394
418
  let session = await this.#ensureSession();
395
419
  let res = await this.#send(method, url, session, options.body);
396
420
  if (res.status === 401 || res.status === 403) {
@@ -904,12 +928,35 @@ function presentAthleteWorkouts(list) {
904
928
  return list.map(presentAthleteWorkout);
905
929
  }
906
930
  /**
931
+ * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
932
+ * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
933
+ * workouts, so a caller wanting one program's session narrows it here. Match by `programId`/`teamId`
934
+ * (exact, on the raw `program_id`/`team_id`) or by `programTitle` (case-insensitive substring on the
935
+ * `program_title`/`team_title`) — the title match lets a caller target a program by name without
936
+ * first resolving its id. Any one match keeps the workout; with no filter the list is unchanged.
937
+ */
938
+ function selectWorkoutsByProgram(list, filter) {
939
+ const { programId, teamId, programTitle } = filter;
940
+ const needle = programTitle?.trim().toLowerCase();
941
+ if (programId === void 0 && teamId === void 0 && !needle) return [...list];
942
+ return list.filter((pw) => {
943
+ const rec = pw;
944
+ if (programId !== void 0 && coerceInt(rec.program_id) === programId) return true;
945
+ if (teamId !== void 0 && coerceInt(rec.team_id) === teamId) return true;
946
+ if (needle) {
947
+ if (`${str$1(rec.program_title) ?? ""} ${str$1(rec.team_title) ?? ""}`.toLowerCase().includes(needle)) return true;
948
+ }
949
+ return false;
950
+ });
951
+ }
952
+ /**
907
953
  * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
908
954
  * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
909
955
  * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
910
956
  * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
911
- * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
912
- * with no resolvable id.
957
+ * `savedWorkoutSetExerciseId` straight off these rows. Each target also carries its program/team
958
+ * so a caller can pick the right session when the athlete is on several. One row per saved set,
959
+ * dropping any set with no resolvable id.
913
960
  */
914
961
  function presentLogTargets(list) {
915
962
  const targets = [];
@@ -920,6 +967,10 @@ function presentLogTargets(list) {
920
967
  if (!saved) continue;
921
968
  const date = str$1(rec.date) ?? "";
922
969
  const workoutTitle = str$1(rec.workout_title) ?? "";
970
+ const program = str$1(rec.program_title);
971
+ const programId = coerceInt(rec.program_id);
972
+ const team = str$1(rec.team_title);
973
+ const teamId = coerceInt(rec.team_id);
923
974
  const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
924
975
  for (const s of sets) {
925
976
  if (!isRecord(s)) continue;
@@ -939,6 +990,10 @@ function presentLogTargets(list) {
939
990
  targets.push({
940
991
  date,
941
992
  workoutTitle,
993
+ program,
994
+ programId,
995
+ team,
996
+ teamId,
942
997
  savedWorkoutSetId,
943
998
  setTitle: str$1(s.title),
944
999
  exercises
@@ -1300,7 +1355,7 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1300
1355
  throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1301
1356
  }
1302
1357
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1303
- if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1358
+ 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.`);
1304
1359
  const body = {
1305
1360
  ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1306
1361
  ...extra
@@ -2758,7 +2813,7 @@ Coach — manage a roster (needs a coach account):
2758
2813
  roster athlete reads (three lenses — pick by the question):
2759
2814
  coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
2760
2815
  coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D team training volume scoped to a date window: per-athlete rows (only those who logged in range) + rolled-up totals (volume in lb). --team resolves the roster; --athletes passes ids directly.
2761
- coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2816
+ coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --program (title substring) / --program-id / --team targets one program when the athlete is on several; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2762
2817
  coach athlete-training --athlete <id> --year <YYYY> --month <1-12> sessions the athlete LOGGED in one month (empty = nothing logged that month, not an error)
2763
2818
  coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
2764
2819
  coach main-lift-prs [--athlete <id>] [--athletes <id,id,...>] [--months <n>] best PRs for the main lifts (squat/bench/deadlift/overhead press/clean & jerk/snatch); auto-discovers the logged variant. With --athlete, one athlete; otherwise the whole roster (or --athletes subset)
@@ -3437,18 +3492,26 @@ async function cmdCoachTeamVolume(client, a) {
3437
3492
  }));
3438
3493
  }
3439
3494
  async function cmdCoachAthleteWorkouts(client, a) {
3440
- const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
3495
+ const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--program <title>|--program-id <id>|--team <id>] [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
3441
3496
  const { values } = parse(a, {
3442
3497
  athlete: { type: "string" },
3443
3498
  start: { type: "string" },
3444
3499
  end: { type: "string" },
3500
+ program: { type: "string" },
3501
+ "program-id": { type: "string" },
3502
+ team: { type: "string" },
3445
3503
  raw: { type: "boolean" },
3446
3504
  "log-ids": { type: "boolean" },
3447
3505
  "logged-only": { type: "boolean" },
3448
3506
  limit: { type: "string" },
3449
3507
  summary: { type: "boolean" }
3450
3508
  });
3451
- const workouts = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3509
+ const all = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3510
+ const filter = {};
3511
+ if (values.program !== void 0) filter.programTitle = values.program;
3512
+ if (values["program-id"] !== void 0) filter.programId = toInt(values["program-id"], "--program-id");
3513
+ if (values.team !== void 0) filter.teamId = toInt(values.team, "--team");
3514
+ const workouts = selectWorkoutsByProgram(all, filter);
3452
3515
  if (values["log-ids"] === true) return out(presentLogTargets(workouts));
3453
3516
  if (values.raw === true) return out(workouts);
3454
3517
  const opts = {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.3.0",
25
- "@trainheroic-unofficial/js": "1.3.0"
24
+ "@trainheroic-unofficial/dto": "1.4.0",
25
+ "@trainheroic-unofficial/js": "1.4.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",