@trainheroic-unofficial/cli 3.7.1 → 4.0.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
@@ -54,7 +54,10 @@ stdin) and writes it into a program on a date. `--program` is a program id (find
54
54
  program's URL in the TrainHeroic web app, or run `trainheroic coach programs`). The spec is
55
55
  `{ blocks, instruction? }` (a bare blocks array is also accepted). Each exercise's `id` is a
56
56
  library id; get one with `coach exercise resolve`. `reps` and `weight` take a scalar or a
57
- per-set array (`"reps": [5, 5, 3]`); loads use the exercise's configured unit. The full schema
57
+ per-set array (`"reps": [5, 5, 3]`). `reps` is the primary value slot and `weight` is the
58
+ secondary slot, so either can represent distance or time on an exercise configured that way.
59
+ State `primaryUnit` for `reps` and `secondaryUnit` for `weight` using the fixed units returned
60
+ by `coach exercise resolve`. The build stops before writing if a unit differs. The full schema
58
61
  is `WorkoutSpec` in [`@trainheroic-unofficial/dto`](../dto).
59
62
 
60
63
  ```jsonc
@@ -64,7 +67,17 @@ is `WorkoutSpec` in [`@trainheroic-unofficial/dto`](../dto).
64
67
  "blocks": [
65
68
  {
66
69
  "title": "Strength",
67
- "exercises": [{ "id": 41822, "sets": 5, "reps": 5, "weight": 225, "rpe": 8 }],
70
+ "exercises": [
71
+ {
72
+ "id": 41822,
73
+ "sets": 5,
74
+ "reps": 5,
75
+ "primaryUnit": "reps",
76
+ "weight": 225,
77
+ "secondaryUnit": "lb",
78
+ "rpe": 8,
79
+ },
80
+ ],
68
81
  },
69
82
  ],
70
83
  }
package/dist/cli.mjs CHANGED
@@ -737,14 +737,26 @@ const exerciseSpecSchema = z.object({
737
737
  z.number(),
738
738
  z.string(),
739
739
  z.array(z.union([z.number(), z.string()]))
740
- ]).optional(),
740
+ ]).optional().describe("Primary slot values; may be reps, distance, or time. State primaryUnit."),
741
741
  sets: z.number().optional(),
742
- weight: z.union([z.number(), z.array(z.number())]).optional(),
742
+ weight: z.union([z.number(), z.array(z.number())]).optional().describe("Secondary slot values; may be weight or time. State secondaryUnit."),
743
+ primaryUnit: z.string().trim().min(1).optional().describe("Intended primary unit from exercise_resolve, such as reps, m, mi, or sec."),
744
+ secondaryUnit: z.string().trim().min(1).optional().describe("Intended secondary unit from exercise_resolve, such as lb or sec."),
743
745
  rpe: z.union([z.number(), z.string()]).optional(),
744
746
  instr: z.string().optional(),
745
747
  param_1_type: z.number().optional(),
746
748
  param_2_type: z.number().optional()
747
749
  }).superRefine((exercise, ctx) => {
750
+ if (exercise.reps !== void 0 && exercise.primaryUnit === void 0) ctx.addIssue({
751
+ code: "custom",
752
+ message: "primaryUnit is required when reps contains primary slot values.",
753
+ path: ["primaryUnit"]
754
+ });
755
+ if (exercise.weight !== void 0 && exercise.secondaryUnit === void 0) ctx.addIssue({
756
+ code: "custom",
757
+ message: "secondaryUnit is required when weight contains secondary slot values.",
758
+ path: ["secondaryUnit"]
759
+ });
748
760
  if (Array.isArray(exercise.reps) && Array.isArray(exercise.weight) && exercise.reps.length !== exercise.weight.length) ctx.addIssue({
749
761
  code: "custom",
750
762
  message: `Per-set reps and weight arrays must have the same length; received ${exercise.reps.length} reps and ${exercise.weight.length} weights.`,
@@ -3502,6 +3514,56 @@ function buildBlockPayload(blocks, workoutId) {
3502
3514
  function unitOr(t) {
3503
3515
  return unitLabel(t) ?? "?";
3504
3516
  }
3517
+ const UNIT_ALIASES = {
3518
+ rep: "reps",
3519
+ reps: "reps",
3520
+ lb: "lb",
3521
+ lbs: "lb",
3522
+ pound: "lb",
3523
+ pounds: "lb",
3524
+ sec: "sec",
3525
+ second: "sec",
3526
+ seconds: "sec",
3527
+ s: "sec",
3528
+ yd: "yd",
3529
+ yard: "yd",
3530
+ yards: "yd",
3531
+ m: "m",
3532
+ meter: "m",
3533
+ meters: "m",
3534
+ metre: "m",
3535
+ metres: "m",
3536
+ mi: "mi",
3537
+ mile: "mi",
3538
+ miles: "mi",
3539
+ ft: "ft",
3540
+ foot: "ft",
3541
+ feet: "ft",
3542
+ in: "in",
3543
+ inch: "in",
3544
+ inches: "in",
3545
+ bpm: "bpm",
3546
+ rpe: "RPE",
3547
+ "%max": "%max"
3548
+ };
3549
+ function statedUnit(value, label) {
3550
+ const normalized = UNIT_ALIASES[value.trim().toLowerCase()];
3551
+ if (normalized === void 0) throw new Error(`${label}: unknown unit '${value}'. Use a concrete exercise unit such as reps, lb, sec, m, or mi.`);
3552
+ return normalized;
3553
+ }
3554
+ function validateSlotUnit(label, field, stated, paramType, fixedType, allowAddedWeight = false) {
3555
+ if (stated === void 0) throw new Error(`${label}: ${field} is required for this value.`);
3556
+ const intended = statedUnit(stated, `${label} / ${field}`);
3557
+ const fixed = unitLabel(fixedType);
3558
+ if (intended !== fixed && !(allowAddedWeight && (fixedType === 0 || fixedType === null) && intended === "lb")) throw new Error(`${label}: ${field} ${intended} does not match the exercise's fixed ${fixed ?? "unset"} unit. Choose an exercise with the requested unit before building.`);
3559
+ if (paramType !== void 0 && unitLabel(paramType) !== intended) throw new Error(`${label}: ${field} ${intended} conflicts with param type ${paramType} (${unitLabel(paramType) ?? "unset"}).`);
3560
+ }
3561
+ /** Validate both populated slots against the library before any workout write. */
3562
+ function validateExerciseUnits(blockTitle, ex, defaults) {
3563
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
3564
+ if (ex.reps !== void 0) validateSlotUnit(label, "primaryUnit", ex.primaryUnit, ex.param_1_type, defaults.param1);
3565
+ if (ex.weight !== void 0) validateSlotUnit(label, "secondaryUnit", ex.secondaryUnit, ex.param_2_type, defaults.param2, true);
3566
+ }
3505
3567
  /** Flag spec params the API will silently override to the exercise's fixed units. */
3506
3568
  function unitAdvisory(blockTitle, ex, defaults) {
3507
3569
  const notes = [];
@@ -3515,8 +3577,8 @@ function unitAdvisory(blockTitle, ex, defaults) {
3515
3577
  warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
3516
3578
  } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
3517
3579
  if (ex.weight !== void 0 && ex.weight !== null) {
3518
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
3519
3580
  const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
3581
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? effP2));
3520
3582
  if (sentP2 !== effP2) {
3521
3583
  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.`);
3522
3584
  else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
@@ -3528,24 +3590,23 @@ function unitAdvisory(blockTitle, ex, defaults) {
3528
3590
  };
3529
3591
  }
3530
3592
  /**
3531
- * Run unit advisories across a whole block list against an exercise index. Shared by the
3532
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
3533
- * index is loaded first, otherwise the defaults map is empty on a cold index and every
3534
- * advisory is silently dropped.
3593
+ * Validate every populated value's stated unit against current TrainHeroic exercise data,
3594
+ * then collect non-blocking advisories. The write path calls this before creating a workout;
3595
+ * TrainHeroic silently replaces mismatched types.
3535
3596
  */
3536
3597
  async function collectAdvisories(blocks, index) {
3537
- await index.ensureFresh();
3538
3598
  const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
3539
3599
  block: b,
3540
3600
  ex
3541
3601
  })));
3542
3602
  const ids = [...new Set(pairs.map((p) => Number(p.ex.id)).filter((id) => Number.isFinite(id)))];
3543
- const defaultsById = await index.defaultsMany(ids);
3603
+ const defaultsById = await index.currentDefaultsMany(ids);
3544
3604
  const notes = [];
3545
3605
  const warnings = [];
3546
3606
  pairs.forEach((p) => {
3547
3607
  const def = defaultsById.get(Number(p.ex.id));
3548
- if (!def) return;
3608
+ if (!def) throw new Error(`${p.block.title} / ${p.ex.title ?? p.ex.id}: exercise id ${p.ex.id} was not found in the library.`);
3609
+ validateExerciseUnits(p.block.title, p.ex, def);
3549
3610
  const advisory = unitAdvisory(p.block.title, p.ex, def);
3550
3611
  notes.push(...advisory.notes);
3551
3612
  warnings.push(...advisory.warnings);
@@ -3586,6 +3647,7 @@ async function buildSession(client, opts) {
3586
3647
  const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
3587
3648
  const splitSummary = setSplitSummary(validatedBlocks);
3588
3649
  if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
3650
+ const advisories = await collectAdvisories(validatedBlocks, opts.index);
3589
3651
  const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
3590
3652
  const sess = await req(client, "POST", createPath(opts), {});
3591
3653
  checkResponse(sessionCreateResponseSchema, sess, "session create");
@@ -3609,7 +3671,8 @@ async function buildSession(client, opts) {
3609
3671
  if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
3610
3672
  return {
3611
3673
  pwId,
3612
- workoutId
3674
+ workoutId,
3675
+ advisories
3613
3676
  };
3614
3677
  }
3615
3678
  /**
@@ -4502,6 +4565,25 @@ const CREATE_PATH = "/2.0/coach/exercise/create";
4502
4565
  const UPDATE_PATH = (id) => `/2.0/coach/exercise/update/${id}`;
4503
4566
  const DELETE_PATH = (id) => `/v5/exercises/${id}`;
4504
4567
  const TTL_MS$1 = 6048e5;
4568
+ /** Read current parameter types without refreshing or trusting the search mirror. */
4569
+ async function fetchCurrentExerciseDefaults(client, ids) {
4570
+ if (ids.length === 0) return /* @__PURE__ */ new Map();
4571
+ const res = await client.request("GET", LIBRARY_PATH);
4572
+ if (!res.ok) throw new Error(`Exercise library fetch failed (HTTP ${res.status}).`);
4573
+ const list = asExerciseList(res.data);
4574
+ if (list.length === 0) throw new Error("Exercise library returned no rows.");
4575
+ checkResponse(exerciseLibraryResponseSchema, list, "exercise library");
4576
+ const requested = new Set(ids);
4577
+ const defaults = /* @__PURE__ */ new Map();
4578
+ for (const exercise of list) {
4579
+ const id = coerceInt(exercise.id);
4580
+ if (id !== null && requested.has(id)) defaults.set(id, {
4581
+ param1: coerceInt(exercise.param_1_type),
4582
+ param2: coerceInt(exercise.param_2_type)
4583
+ });
4584
+ }
4585
+ return defaults;
4586
+ }
4505
4587
  function toStored(ex) {
4506
4588
  const id = coerceInt(ex.id);
4507
4589
  if (id === null) return null;
@@ -4602,6 +4684,9 @@ var ExerciseLibrary = class {
4602
4684
  }
4603
4685
  return result;
4604
4686
  }
4687
+ async currentDefaultsMany(ids) {
4688
+ return fetchCurrentExerciseDefaults(this.#client, ids);
4689
+ }
4605
4690
  async search(query, limit = 20) {
4606
4691
  await this.ensureFresh();
4607
4692
  return this.#searchOnly(query, limit);
@@ -5057,20 +5142,19 @@ async function cmdWorkoutBuild(client, a) {
5057
5142
  const opts = {
5058
5143
  programId,
5059
5144
  blocks: spec.blocks,
5145
+ index: library(client),
5060
5146
  publish
5061
5147
  };
5062
5148
  if (splitSummary !== null) opts.confirmSetSplit = true;
5063
5149
  if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
5064
5150
  if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
5065
5151
  if (spec.instruction !== void 0) opts.instruction = spec.instruction;
5066
- const advice = await collectAdvisories(spec.blocks, library(client));
5067
5152
  const built = await buildSession(client, opts);
5068
5153
  const readback = opts.date ? await readSession(client, programId, opts.date, built.pwId) : null;
5069
5154
  return out({
5070
5155
  ...built,
5071
5156
  programId,
5072
5157
  published: publish,
5073
- advisories: advice,
5074
5158
  readback
5075
5159
  });
5076
5160
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "3.7.1",
3
+ "version": "4.0.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.6.3",
24
- "@trainheroic-unofficial/dto": "3.7.1",
25
- "@trainheroic-unofficial/js": "3.7.1"
24
+ "@trainheroic-unofficial/dto": "4.0.0",
25
+ "@trainheroic-unofficial/js": "4.0.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.5.1",
@@ -139,18 +139,18 @@ explicit confirmation before publishing. Build a draft (the default), show the r
139
139
  for review, and only publish once the user confirms.
140
140
 
141
141
  `$TH coach workout build` runs the whole sequence (program → session → blocks → exercises),
142
- fills every field that otherwise makes the exercise step return HTTP 500, encodes
143
- prescriptions correctly, and prints unit advisories plus a read-back. Feed it a JSON spec
142
+ fills every field that otherwise makes the exercise step return HTTP 500, validates
143
+ the stated units against the exercise library, and prints a read-back. Feed it a JSON spec
144
144
  (inline, `--file`, or stdin):
145
145
 
146
146
  ```bash
147
147
  cat > day.json <<'JSON'
148
148
  { "blocks": [
149
149
  { "title": "Primary Press", "exercises": [
150
- { "id": 1162, "title": "Bench Press", "reps": [10,10,8,8], "rpe": 8 } ] },
150
+ { "id": 1162, "title": "Bench Press", "reps": [10,10,8,8], "primaryUnit": "reps", "rpe": 8 } ] },
151
151
  { "title": "Accessory", "instruction": "Superset", "exercises": [
152
- { "id": 903, "title": "Dips", "sets": 3, "reps": 12, "rpe": 8 },
153
- { "id": 6535, "title": "Tricep Pushdown", "reps": [15,15,15], "rpe": 8 } ] }
152
+ { "id": 903, "title": "Dips", "sets": 3, "reps": 12, "primaryUnit": "reps", "rpe": 8 },
153
+ { "id": 6535, "title": "Tricep Pushdown", "reps": [15,15,15], "primaryUnit": "reps", "rpe": 8 } ] }
154
154
  ] }
155
155
  JSON
156
156
 
@@ -245,8 +245,10 @@ Environment-specific facts that defy reasonable assumptions:
245
245
  coerce to weight on a weight lift, rendering as pounds — put % or RPE in the
246
246
  `instruction` (the builder does this from `rpe`). You _can_ add weight (`1`) to a
247
247
  no-secondary-param lift (weighted Pull-Ups). Check units with `$TH coach exercise resolve`
248
- (the `units` array, ordered by entry slot `[param 1, param 2]`); the builder prints a
249
- warning when a sent type will be overridden. "Max"/"AMRAP" reps work as free text in the
248
+ (the `units` array, ordered by entry slot `[param 1, param 2]`). Include
249
+ `primaryUnit` with every `reps` value and `secondaryUnit` with every `weight` value;
250
+ these fields name the intended unit for each positional slot. The builder rejects
251
+ mismatches before creating a draft. "Max"/"AMRAP" reps work as free text in the
250
252
  rep slots.
251
253
  - **`saveWorkoutSetExercises` returns HTTP 500** unless every field is present: all ten
252
254
  `param_1_data_N`/`param_2_data_N` slots (empty string for unused), `set_num`, `key`,
@@ -230,9 +230,10 @@ sent under the wrong assumed unit silently renders under the exercise's real uni
230
230
  weighted Pull-Ups/Dips work. `2` (% of max) and `14` (RPE) do **not** stick on a
231
231
  weight-default lift; both coerce to weight and render as pounds.
232
232
  - Check an exercise's real units first: `$TH coach exercise resolve "<name>"` prints a
233
- `units` array, ordered by entry slot (`[param 1, param 2]`). the workout builder also
234
- prints a `WARNING` when a sent param type will be overridden, and its read-back labels
235
- the stored units.
233
+ `units` array, ordered by entry slot (`[param 1, param 2]`). In the workout spec,
234
+ include `primaryUnit` when `reps` contains a value and `secondaryUnit` when `weight`
235
+ contains a value. The builder checks both units before creating a draft, and its
236
+ read-back labels the stored units.
236
237
 
237
238
  ## Prescription patterns
238
239