@trainheroic-unofficial/cli 1.7.2 → 1.7.3

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 +109 -105
  2. package/package.json +6 -6
package/dist/cli.mjs CHANGED
@@ -172,6 +172,26 @@ const loggedSetSchema = z.object({
172
172
  * always sequential).
173
173
  */
174
174
  const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().min(1).max(10).optional() });
175
+ function requireUniqueExerciseIds(results, ctx) {
176
+ const seen = /* @__PURE__ */ new Set();
177
+ results.forEach((result, index) => {
178
+ const id = String(result.savedWorkoutSetExerciseId).replace(/^0+(?=\d)/u, "");
179
+ if (seen.has(id)) ctx.addIssue({
180
+ code: "custom",
181
+ message: `savedWorkoutSetExerciseId ${id} appears more than once; combine its sets into one result.`,
182
+ path: [index, "savedWorkoutSetExerciseId"]
183
+ });
184
+ seen.add(id);
185
+ });
186
+ }
187
+ const loggedExerciseResultsSchema = z.array(z.object({
188
+ savedWorkoutSetExerciseId: idArgSchema,
189
+ sets: z.array(loggedSetWithSlotSchema).min(1)
190
+ })).min(1).superRefine(requireUniqueExerciseIds);
191
+ const prescribedExerciseResultsSchema = z.array(z.object({
192
+ savedWorkoutSetExerciseId: idArgSchema,
193
+ sets: z.array(loggedSetSchema).min(1)
194
+ })).min(1).superRefine(requireUniqueExerciseIds);
175
195
  /**
176
196
  * Args for the set-logging write. `date` (the workout's day) locates the saved
177
197
  * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
@@ -183,10 +203,7 @@ const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().
183
203
  const logSetArgsSchema = z.object({
184
204
  date: dateString,
185
205
  savedWorkoutSetId: idArgSchema,
186
- results: z.array(z.object({
187
- savedWorkoutSetExerciseId: idArgSchema,
188
- sets: z.array(loggedSetWithSlotSchema).min(1)
189
- })).min(1)
206
+ results: loggedExerciseResultsSchema
190
207
  });
191
208
  /**
192
209
  * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
@@ -206,10 +223,7 @@ const coachPrescribeSetArgsSchema = z.object({
206
223
  date: dateString,
207
224
  savedWorkoutSetId: idArgSchema,
208
225
  athleteId: idArgSchema,
209
- results: z.array(z.object({
210
- savedWorkoutSetExerciseId: idArgSchema,
211
- sets: z.array(loggedSetSchema).min(1)
212
- })).min(1)
226
+ results: prescribedExerciseResultsSchema
213
227
  });
214
228
  /**
215
229
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
@@ -1330,6 +1344,75 @@ function presentExerciseHistory(detail) {
1330
1344
  };
1331
1345
  }
1332
1346
  //#endregion
1347
+ //#region ../js/src/exercise-set-payload.ts
1348
+ function slotData(exercise, key) {
1349
+ const value = exercise?.[key];
1350
+ return value === void 0 || value === null ? "" : String(value);
1351
+ }
1352
+ function slotIsActive(exercise, slot, targeted = false) {
1353
+ return targeted || slotData(exercise, `param_1_data_${slot}`) !== "" || slotData(exercise, `param_2_data_${slot}`) !== "" || coerceInt(exercise?.[`param_${slot}_made`]) === 1;
1354
+ }
1355
+ /** True when an existing saved-copy exercise has at least one active slot and all are performed. */
1356
+ function exerciseIsFullyLogged(exercise) {
1357
+ let anyActive = false;
1358
+ for (let slot = 1; slot <= 10; slot += 1) {
1359
+ if (!slotIsActive(exercise, slot)) continue;
1360
+ anyActive = true;
1361
+ if (coerceInt(exercise[`param_${slot}_made`]) !== 1) return false;
1362
+ }
1363
+ return anyActive;
1364
+ }
1365
+ /**
1366
+ * Build the typed body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`.
1367
+ *
1368
+ * A log marks only slots carrying reps as performed. The exercise completes only when every active
1369
+ * slot is performed; active slots are prescribed values, prior performed values, or slots targeted
1370
+ * by this write. Untargeted performed slots carry over, while untouched prescription values are
1371
+ * blanked so TrainHeroic cannot fabricate performed results from them. A prescription replaces the
1372
+ * full payload and never marks slots or the exercise complete.
1373
+ */
1374
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1375
+ if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1376
+ const bySlot = /* @__PURE__ */ new Map();
1377
+ results.forEach((set, index) => {
1378
+ const slot = set.slot ?? index + 1;
1379
+ if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1380
+ if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1381
+ bySlot.set(slot, set);
1382
+ });
1383
+ const logging = mode === "log";
1384
+ const body = {
1385
+ id: savedWorkoutSetExerciseId,
1386
+ saved_workout_set_id: savedWorkoutSetId,
1387
+ workout_set_exercise_id: workoutSetExerciseId,
1388
+ completed: 0
1389
+ };
1390
+ let anyMade = false;
1391
+ let allActiveSlotsMade = true;
1392
+ for (let slot = 1; slot <= 10; slot += 1) {
1393
+ const target = bySlot.get(slot);
1394
+ let param1 = "";
1395
+ let param2 = "";
1396
+ let made = 0;
1397
+ if (target) {
1398
+ param1 = target.param1 === void 0 ? "" : String(target.param1);
1399
+ param2 = target.param2 === void 0 ? "" : String(target.param2);
1400
+ made = logging && param1 !== "" ? 1 : 0;
1401
+ } else if (logging && coerceInt(existing?.[`param_${slot}_made`]) === 1) {
1402
+ param1 = slotData(existing, `param_1_data_${slot}`);
1403
+ param2 = slotData(existing, `param_2_data_${slot}`);
1404
+ made = 1;
1405
+ }
1406
+ anyMade ||= made === 1;
1407
+ if (slotIsActive(existing, slot, target !== void 0) && made !== 1) allActiveSlotsMade = false;
1408
+ body[`param_${slot}_made`] = made;
1409
+ body[`param_1_data_${slot}`] = param1;
1410
+ body[`param_2_data_${slot}`] = param2;
1411
+ }
1412
+ body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
1413
+ return body;
1414
+ }
1415
+ //#endregion
1333
1416
  //#region ../js/src/athlete-set-write.ts
1334
1417
  /**
1335
1418
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -1355,107 +1438,25 @@ function toSetResults(results) {
1355
1438
  });
1356
1439
  }
1357
1440
  /**
1358
- * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
1359
- * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
1360
- * `param_2_data_N` string values plus a `param_N_made` flag.
1361
- *
1362
- * `mode` selects which write this is — the same endpoint serves both:
1363
- * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has reps
1364
- * entered (`param1`) and the exercise `completed` flag is 1 when any set is performed. A slot
1365
- * carrying only a weight (`param2`) with no reps is a target, not a performed set, so it stays
1366
- * un-made — matching the app, which shows no completion checkmark until reps are logged.
1367
- * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1368
- * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1369
- * coach edits an athlete's prescribed reps/weight.
1370
- *
1371
- * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1372
- * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1373
- * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1374
- * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1375
- * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1376
- * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1377
- * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1378
- * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1379
- *
1380
- * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1381
- * required from the live exercise record; everything else is derived from `results` and the
1382
- * preserved slots of `existing`.
1383
- *
1384
- * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1441
+ * Whether every exercise in a saved workout set is fully logged — either completed by its projected
1442
+ * payload in this call (`projectedCompletion`) or already carrying made flags for every active slot.
1443
+ * This gates the set-completion PUT so a partial exercise cannot close a superset/circuit and cause
1444
+ * TrainHeroic to backfill its omitted slots or untouched siblings.
1385
1445
  */
1386
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1387
- if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1388
- const bySlot = /* @__PURE__ */ new Map();
1389
- results.forEach((set, i) => {
1390
- const slot = set.slot ?? i + 1;
1391
- if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1392
- if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1393
- bySlot.set(slot, set);
1394
- });
1395
- const performed = mode === "log";
1396
- const carryOver = performed && existing !== void 0;
1397
- const body = {
1398
- id: savedWorkoutSetExerciseId,
1399
- saved_workout_set_id: savedWorkoutSetId,
1400
- workout_set_exercise_id: workoutSetExerciseId
1401
- };
1402
- let anyMade = false;
1403
- for (let i = 1; i <= 10; i += 1) {
1404
- const target = bySlot.get(i);
1405
- let p1;
1406
- let p2;
1407
- let made;
1408
- if (target) {
1409
- p1 = target.param1 !== void 0 ? String(target.param1) : "";
1410
- p2 = target.param2 !== void 0 ? String(target.param2) : "";
1411
- made = performed && p1 !== "" ? 1 : 0;
1412
- } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1413
- p1 = existingSlotData(existing, `param_1_data_${i}`);
1414
- p2 = existingSlotData(existing, `param_2_data_${i}`);
1415
- made = 1;
1416
- } else {
1417
- p1 = "";
1418
- p2 = "";
1419
- made = 0;
1420
- }
1421
- if (made === 1) anyMade = true;
1422
- body[`param_${i}_made`] = made;
1423
- body[`param_1_data_${i}`] = p1;
1424
- body[`param_2_data_${i}`] = p2;
1425
- }
1426
- body.completed = performed && anyMade ? 1 : 0;
1427
- return body;
1428
- }
1429
- /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1430
- function existingSlotData(existing, key) {
1431
- const v = existing?.[key];
1432
- return v === void 0 || v === null ? "" : String(v);
1433
- }
1434
- /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1435
- function exerciseHasLoggedData(ex) {
1436
- for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1437
- return false;
1438
- }
1439
- /** True when a result carries at least one set with reps entered (so it produces a performed slot).
1440
- * A weight-only set (`param2` set, `param1` blank) is a target, not a performed result, and so does
1441
- * not count — mirroring the `made` rule in {@link buildExerciseSetPayload}. */
1442
- function resultHasPerformedSet(result) {
1443
- return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "");
1444
- }
1445
- /**
1446
- * Whether every exercise in a saved workout set now has logged data — either written with data in
1447
- * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1448
- * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1449
- * does not flip its still-empty siblings to "done". An exercise written with no reps — empty values,
1450
- * or a weight (`param2`) with no reps (`param1`) — does not count (it would not be marked performed),
1451
- * so a no-reps log never completes the set.
1452
- */
1453
- function isSetFullyLogged(exercises, loggedIds) {
1446
+ function isSetFullyLogged(exercises, projectedCompletion) {
1454
1447
  return exercises.every((ex) => {
1455
1448
  const id = coerceInt(ex.id);
1456
- return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1449
+ if (id !== null && projectedCompletion.has(id)) return projectedCompletion.get(id) === true;
1450
+ return exerciseIsFullyLogged(ex);
1457
1451
  });
1458
1452
  }
1453
+ function assertUniqueExerciseResults(results) {
1454
+ const seen = /* @__PURE__ */ new Set();
1455
+ for (const result of results) {
1456
+ if (seen.has(result.savedWorkoutSetExerciseId)) throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} appears more than once; combine its sets into one result.`);
1457
+ seen.add(result.savedWorkoutSetExerciseId);
1458
+ }
1459
+ }
1459
1460
  /**
1460
1461
  * Locate the target saved workout set across all program workouts on the given day.
1461
1462
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1655,9 +1656,11 @@ async function swapAthleteExercise(client, args) {
1655
1656
  */
1656
1657
  async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1657
1658
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1659
+ assertUniqueExerciseResults(results);
1658
1660
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1659
1661
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1660
1662
  let exercisesWritten = 0;
1663
+ const projectedCompletion = /* @__PURE__ */ new Map();
1661
1664
  for (const result of results) {
1662
1665
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1663
1666
  if (!ex) {
@@ -1678,11 +1681,12 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1678
1681
  const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
1679
1682
  throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1680
1683
  }
1684
+ projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
1681
1685
  exercisesWritten += 1;
1682
1686
  }
1683
1687
  let setCompleted = false;
1684
1688
  if (mode === "log") {
1685
- if (isSetFullyLogged(exercises, new Set(results.filter(resultHasPerformedSet).map((r) => r.savedWorkoutSetExerciseId)))) {
1689
+ if (isSetFullyLogged(exercises, projectedCompletion)) {
1686
1690
  const setBody = {
1687
1691
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1688
1692
  ...extra
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.7.2",
3
+ "version": "1.7.3",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,15 +21,15 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.7.2",
25
- "@trainheroic-unofficial/js": "1.7.2"
24
+ "@trainheroic-unofficial/dto": "1.7.3",
25
+ "@trainheroic-unofficial/js": "1.7.3"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.0.1",
28
+ "@types/node": "^26.1.0",
29
29
  "tsdown": "^0.22.3",
30
- "tsx": "^4.22.4",
30
+ "tsx": "^4.23.0",
31
31
  "typescript": "^6.0.3",
32
- "vitest": "^4.1.9"
32
+ "vitest": "^4.1.10"
33
33
  },
34
34
  "scripts": {
35
35
  "start": "tsx src/cli.ts",