@trainheroic-unofficial/js 3.5.0 → 3.5.2

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
@@ -1,5 +1,6 @@
1
1
  import { n as LibrarySnapshot, r as MemoryLibraryCache, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
2
  import { Advisory, AthleteExerciseNoteOutput, AthletePrefs, AthleteProfileSummary, AthleteUser, AthleteWorkingMax, AthleteWorkoutNoteOutput, AthleteWorkoutSummary, AthleteWorkoutView, BlockSpec, CoachAthleteTraining, ExerciseHistoryDetail, ExerciseHistoryListItem, ExerciseRow, ExerciseSpec, ExerciseStats, ExerciseView, PersonalRecord, PresentedExerciseHistory, ProgramWorkout, ReadResult, ResolveResult, RosterActivityRow, SessionTemplateCreate, TeamPublishPatch, TeamVolumeReport, WorkoutDate, WorkoutHistoryExport } from "@trainheroic-unofficial/dto";
3
+ import { chunk } from "es-toolkit/array";
3
4
  import { ZodType } from "zod";
4
5
  export * from "@trainheroic-unofficial/dto";
5
6
  //#region src/http-error.d.ts
@@ -160,13 +161,27 @@ declare function rankSearch<T extends {
160
161
  title: string;
161
162
  can_edit?: number;
162
163
  }>(rows: readonly T[], query: string, limit: number): T[];
163
- declare function chunk<T>(items: readonly T[], size: number): T[][];
164
164
  /**
165
165
  * Map over items with a bounded number of concurrent workers. Used to fan out upstream
166
166
  * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
167
167
  * on workerd, blowing the subrequest budget.
168
168
  */
169
169
  declare function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
170
+ /**
171
+ * A concurrency limiter shared across independent call sites: at most `max` tasks run at once,
172
+ * the rest wait in FIFO order. Where {@link mapPool} bounds one fan-out, a limiter bounds the sum
173
+ * of several nested ones (a session write that fans out per set, each of which fans out per
174
+ * exercise) to a single ceiling. `cancel` stops the queue: tasks not yet started, and any run
175
+ * after it, reject with the given error, while tasks already running finish normally, so one
176
+ * failed write halts the rest of a session without abandoning requests already on the wire.
177
+ */
178
+ type Limiter = {
179
+ run<T>(task: () => Promise<T>): Promise<T>;
180
+ /** Run required finalization even after cancellation, while preserving the same concurrency cap. */
181
+ runFinalizer<T>(task: () => Promise<T>): Promise<T>;
182
+ cancel(error: unknown): void;
183
+ };
184
+ declare function createLimiter(max: number): Limiter;
170
185
  /**
171
186
  * The exercise-library surface the tools depend on, so the tools work over either a
172
187
  * D1-backed mirror (hosted, multi-tenant) or an in-memory cache (local, single-user).
@@ -221,7 +236,12 @@ declare function fetchExerciseHistoryList(client: TrainHeroicClient): Promise<Ex
221
236
  declare function fetchRecentExercises(client: TrainHeroicClient): Promise<unknown[]>;
222
237
  declare function fetchAthleteCircuits(client: TrainHeroicClient, kind?: "recent" | "history"): Promise<unknown[]>;
223
238
  declare function fetchAthleteProgrammingPrograms(client: TrainHeroicClient): Promise<unknown[]>;
224
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
239
+ /**
240
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
241
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
242
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
243
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
244
+ */
225
245
  declare function searchExerciseHistory(client: TrainHeroicClient, query: string, limit?: number): Promise<ExerciseHistoryListItem[]>;
226
246
  declare function fetchExerciseHistoryDetail(client: TrainHeroicClient, exerciseId: number, userId: number): Promise<ExerciseHistoryDetail>;
227
247
  declare function fetchPersonalRecords(client: TrainHeroicClient, exerciseId: number): Promise<PersonalRecord[]>;
@@ -262,6 +282,16 @@ declare function fetchLeaderboard(client: TrainHeroicClient, workoutId: number,
262
282
  pageSize?: number;
263
283
  gender?: number;
264
284
  }): Promise<unknown>;
285
+ /**
286
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
287
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
288
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
289
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
290
+ */
291
+ declare function performedExercises(workouts: readonly ProgramWorkout[]): Array<{
292
+ exerciseId: number;
293
+ title: string;
294
+ }>;
265
295
  /**
266
296
  * Flatten one range item into a readable workout: each exercise carries its `prescribed` and
267
297
  * `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
@@ -350,6 +380,16 @@ declare function presentCoachAthleteTraining(raw: readonly unknown[], athleteId:
350
380
  /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
351
381
  declare function presentExerciseHistory(detail: ExerciseHistoryDetail): PresentedExerciseHistory;
352
382
  //#endregion
383
+ //#region src/exercise-history.d.ts
384
+ /**
385
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
386
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
387
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
388
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
389
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
390
+ */
391
+ declare function historyInRange(presented: PresentedExerciseHistory, since: string | undefined, until: string | undefined): PresentedExerciseHistory;
392
+ //#endregion
353
393
  //#region src/coach-athlete-calendar.d.ts
354
394
  /**
355
395
  * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
@@ -1005,6 +1045,12 @@ declare function definedProps<T extends object>(obj: T): { [K in keyof T]: Exclu
1005
1045
  //#endregion
1006
1046
  //#region src/workout-encode.d.ts
1007
1047
  type AdvisoryIndex = Pick<ExerciseIndex, "defaultsMany" | "ensureFresh">;
1048
+ type SetSplit = {
1049
+ blockTitle: string;
1050
+ exerciseTitle: string;
1051
+ setCount: number;
1052
+ blockCount: number;
1053
+ };
1008
1054
  declare const LEADERBOARD_TYPE: Readonly<Record<string, number>>;
1009
1055
  declare const LEADERBOARD_LABEL: Readonly<Record<number, string>>;
1010
1056
  type Leaderboard = {
@@ -1015,6 +1061,16 @@ type Leaderboard = {
1015
1061
  };
1016
1062
  declare function resolveLeaderboard(block: BlockSpec): Leaderboard;
1017
1063
  declare function repsList(ex: ExerciseSpec): string[];
1064
+ /** Number of sets that the encoder will write for an exercise. */
1065
+ declare function exerciseSetCount(ex: ExerciseSpec): number;
1066
+ declare function findSetSplits(blocks: readonly BlockSpec[]): SetSplit[];
1067
+ declare function setSplitSummary(blocks: readonly BlockSpec[]): string | null;
1068
+ /**
1069
+ * Split blocks so no encoded exercise exceeds TrainHeroic's ten parameter slots.
1070
+ * Exercises in a superset stay aligned by set range; shorter exercises appear only in
1071
+ * chunks where they still have sets.
1072
+ */
1073
+ declare function splitOversizedBlocks(blocks: readonly BlockSpec[]): BlockSpec[];
1018
1074
  /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
1019
1075
  declare function makeExercise(ex: ExerciseSpec, workoutSetId: number, order: number, key: string): Record<string, unknown>;
1020
1076
  /** Block `type` values the coach calendar accepts (verified in workout-creation.md). */
@@ -1046,6 +1102,8 @@ type BuildOptions = {
1046
1102
  date?: WorkoutDate;
1047
1103
  timelineDay?: number;
1048
1104
  publish?: boolean;
1105
+ /** Explicitly allow prescriptions above ten sets to become consecutive blocks. */
1106
+ confirmSetSplit?: boolean;
1049
1107
  /** Optional session-level note ("Coach Instructions"), set after the blocks save. */
1050
1108
  instruction?: string;
1051
1109
  };
@@ -1107,4 +1165,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
1107
1165
  stats(): Promise<Record<string, unknown>>;
1108
1166
  }
1109
1167
  //#endregion
1110
- export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, DEFAULT_INVITE_MESSAGE, DeletedProgram, ExerciseDefaults, 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, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, RequestOptions, ResolvedLift, SESSION_TEMPLATES_LIST_PATH, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, type SetWriteMode, SwapExerciseResult, TeamPublishTarget, 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, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
1168
+ export { ANALYTICS_METRIC_KEYS, AddedExercise, AnalyticsMetric, AnalyticsQueryArgs, ApiBase, AthleteMainLiftPRs, BLOCK_TYPE_CONDITIONING, BLOCK_TYPE_HYPERTROPHY, BuildOptions, ClientOptions, ClientResult, CoachAthleteCalendar, CoachRosterAthlete, CreatedProgram, DEFAULT_INVITE_MESSAGE, DeletedProgram, ExerciseDefaults, ExerciseIndex, ExerciseLibrary, type ExerciseSetInput, type ExerciseSetPayload, LEADERBOARD_LABEL, LEADERBOARD_TYPE, Leaderboard, LibraryCache, LibrarySnapshot, Limiter, 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, PROGRAM_KINDS, PersonalWorkoutCreated, ProgramKind, RequestOptions, ResolvedLift, SESSION_TEMPLATES_LIST_PATH, ScheduledAlternative, SerializedExport, SessionExercise, SetResult, SetSplit, type SetWriteMode, SwapExerciseResult, TeamPublishTarget, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, type TrainHeroicHttpErrorHandler, TrainHeroicSession, WorkoutExportFormat, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema, parseWorkoutDate, programCreateResponseSchema, programsEditResponseSchema, sessionCreateResponseSchema } from "@trainheroic-unofficial/dto";
2
+ import { chunk, uniq } from "es-toolkit/array";
2
3
  import { z } from "zod";
3
4
  export * from "@trainheroic-unofficial/dto";
4
5
  //#region src/http-error.ts
@@ -370,29 +371,82 @@ function rankSearch(rows, query, limit) {
370
371
  };
371
372
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
372
373
  }
373
- function chunk(items, size) {
374
- const out = [];
375
- for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
376
- return out;
377
- }
378
374
  /**
379
375
  * Map over items with a bounded number of concurrent workers. Used to fan out upstream
380
376
  * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
381
377
  * on workerd, blowing the subrequest budget.
382
378
  */
383
379
  async function mapPool(items, limit, fn) {
380
+ assertPositiveInteger(limit, "Concurrency limit");
384
381
  const out = Array.from({ length: items.length });
385
382
  let next = 0;
383
+ const state = { failure: null };
386
384
  const worker = async () => {
387
- while (next < items.length) {
385
+ while (next < items.length && state.failure === null) {
388
386
  const i = next;
389
387
  next += 1;
390
- out[i] = await fn(items[i], i);
388
+ try {
389
+ out[i] = await fn(items[i], i);
390
+ } catch (error) {
391
+ state.failure ??= { error };
392
+ }
391
393
  }
392
394
  };
393
395
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
396
+ if (state.failure !== null) throw state.failure.error;
394
397
  return out;
395
398
  }
399
+ function createLimiter(max) {
400
+ assertPositiveInteger(max, "Maximum concurrency");
401
+ let active = 0;
402
+ let cancelled = null;
403
+ const waiting = [];
404
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
405
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
406
+ else if (active < max) {
407
+ active += 1;
408
+ resolve();
409
+ } else waiting.push({
410
+ start: () => {
411
+ active += 1;
412
+ resolve();
413
+ },
414
+ abort: reject,
415
+ finalizer
416
+ });
417
+ });
418
+ const release = () => {
419
+ active -= 1;
420
+ waiting.shift()?.start();
421
+ };
422
+ return {
423
+ async run(task) {
424
+ await acquire(false);
425
+ try {
426
+ return await task();
427
+ } finally {
428
+ release();
429
+ }
430
+ },
431
+ async runFinalizer(task) {
432
+ await acquire(true);
433
+ try {
434
+ return await task();
435
+ } finally {
436
+ release();
437
+ }
438
+ },
439
+ cancel(error) {
440
+ cancelled ??= { error };
441
+ const queued = waiting.splice(0);
442
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
443
+ else entry.abort(error);
444
+ }
445
+ };
446
+ }
447
+ function assertPositiveInteger(value, label) {
448
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
449
+ }
396
450
  //#endregion
397
451
  //#region src/athlete.ts
398
452
  async function getJson(client, path, label) {
@@ -446,39 +500,25 @@ function sortRosterByRecency(rows) {
446
500
  * summary becomes a null-data row (sorted last), not an error.
447
501
  */
448
502
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
449
- const rows = [];
450
- const concurrency = 6;
451
- const uniqueAthleteIds = [...new Set(athleteIds)];
452
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
453
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
454
- const settled = await Promise.all(chunk.map(async (id) => {
455
- try {
456
- return {
457
- id,
458
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
459
- };
460
- } catch {
461
- return {
462
- id,
463
- summary: null
464
- };
465
- }
466
- }));
467
- for (const { id, summary } of settled) {
468
- const count = summary?.sessions_count ?? null;
469
- const hasSessions = count !== null && count > 0;
470
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
471
- rows.push({
472
- athleteId: id,
473
- sessionsCount: count,
474
- firstLoggedDate: normDate(summary?.first_logged_date),
475
- lastLoggedDate: normDate(summary?.last_logged_date),
476
- totalReps: summary?.reps_sum ?? null,
477
- totalVolume: summary?.volume_sum ?? null
478
- });
503
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
504
+ let summary;
505
+ try {
506
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
507
+ } catch {
508
+ summary = null;
479
509
  }
480
- }
481
- return sortRosterByRecency(rows);
510
+ const count = summary?.sessions_count ?? null;
511
+ const hasSessions = count !== null && count > 0;
512
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
513
+ return {
514
+ athleteId: id,
515
+ sessionsCount: count,
516
+ firstLoggedDate: normDate(summary?.first_logged_date),
517
+ lastLoggedDate: normDate(summary?.last_logged_date),
518
+ totalReps: summary?.reps_sum ?? null,
519
+ totalVolume: summary?.volume_sum ?? null
520
+ };
521
+ }));
482
522
  }
483
523
  function fetchAthletePrefs(client) {
484
524
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
@@ -498,9 +538,19 @@ function fetchAthleteCircuits(client, kind = "recent") {
498
538
  function fetchAthleteProgrammingPrograms(client) {
499
539
  return getArray$1(client, "/1.0/athlete/programming/programs", "athlete programming programs");
500
540
  }
501
- /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
541
+ /**
542
+ * Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). Only
543
+ * rows whose title carries every query token are candidates; rankSearch scores but never drops a
544
+ * row, so ranking the whole catalog would pad a no-match query with the shortest titles up to
545
+ * `limit`. Mirrors the coach `ExerciseLibrary.search` filter, and a blank query returns nothing.
546
+ */
502
547
  async function searchExerciseHistory(client, query, limit = 20) {
503
- return rankSearch(await fetchExerciseHistoryList(client), query, limit);
548
+ const tokens = buildSearchText(query).split(/\s+/u).filter((t) => t.length > 0);
549
+ if (tokens.length === 0) return [];
550
+ return rankSearch((await fetchExerciseHistoryList(client)).filter((row) => {
551
+ const text = buildSearchText(row.title);
552
+ return tokens.every((t) => text.includes(t));
553
+ }), query, limit);
504
554
  }
505
555
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
506
556
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -615,6 +665,28 @@ function slotValues(ex, requireMade) {
615
665
  }
616
666
  return map;
617
667
  }
668
+ /**
669
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
670
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
671
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
672
+ * only prescription, since personal work has no template tree at all.
673
+ */
674
+ function unmadeSlotValues(ex) {
675
+ const map = slotValues(ex, false);
676
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
677
+ return map;
678
+ }
679
+ /**
680
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
681
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
682
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
683
+ * slots are the whole prescription.
684
+ */
685
+ function prescriptionSlots(template, saved) {
686
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
687
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
688
+ return map;
689
+ }
618
690
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
619
691
  function fmtSlot(slot) {
620
692
  const has1 = slot.p1 !== null;
@@ -624,10 +696,6 @@ function fmtSlot(slot) {
624
696
  if (has2) return `@ ${slot.p2}`;
625
697
  return "";
626
698
  }
627
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
628
- function prescribedStrings(ex) {
629
- return [...slotValues(ex, false).values()].map(fmtSlot);
630
- }
631
699
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
632
700
  function performedStrings(ex) {
633
701
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -649,6 +717,46 @@ function savedSets(saved) {
649
717
  return out;
650
718
  }
651
719
  /**
720
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
721
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
722
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
723
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
724
+ */
725
+ function performedExercises(workouts) {
726
+ const out = [];
727
+ for (const pw of workouts) {
728
+ const rec = pw;
729
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
730
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
731
+ const templates = /* @__PURE__ */ new Map();
732
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
733
+ if (!isRecord(set)) continue;
734
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
735
+ for (const ex of exercises) {
736
+ if (!isRecord(ex)) continue;
737
+ const id = coerceInt(ex.id);
738
+ if (id !== null) templates.set(id, {
739
+ exerciseId: coerceInt(ex.exercise_id),
740
+ title: exerciseTitle(ex)
741
+ });
742
+ }
743
+ }
744
+ const saved = savedWorkoutOf(pw);
745
+ if (!saved) continue;
746
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
747
+ const templateId = coerceInt(ex.workout_set_exercise_id);
748
+ const template = templateId === null ? void 0 : templates.get(templateId);
749
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
750
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
751
+ out.push({
752
+ exerciseId,
753
+ title: exerciseTitle(ex, template?.title)
754
+ });
755
+ }
756
+ }
757
+ return out;
758
+ }
759
+ /**
652
760
  * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
653
761
  * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
654
762
  * entered values live in the same `param_N_data` slots as a prescription.
@@ -663,6 +771,15 @@ function performedSlotsByExerciseId(sets) {
663
771
  }
664
772
  return map;
665
773
  }
774
+ /** Each saved-copy row keyed by the prescription exercise id it was copied from. */
775
+ function savedRowsByTemplateId(sets) {
776
+ const map = /* @__PURE__ */ new Map();
777
+ for (const { exercises } of sets) for (const ex of exercises) {
778
+ const id = coerceInt(ex.workout_set_exercise_id);
779
+ if (id !== null && !map.has(id)) map.set(id, ex);
780
+ }
781
+ return map;
782
+ }
666
783
  /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
667
784
  function notesByTemplateId(sets) {
668
785
  const map = /* @__PURE__ */ new Map();
@@ -686,7 +803,7 @@ function mergeExercise(prescribed, performed, meta) {
686
803
  };
687
804
  }
688
805
  /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
689
- function mergePrescriptionBlock(set, performedById, notesById) {
806
+ function mergePrescriptionBlock(set, performedById, savedById, notesById) {
690
807
  const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
691
808
  return {
692
809
  order: coerceInt(set.order) ?? 0,
@@ -696,7 +813,7 @@ function mergePrescriptionBlock(set, performedById, notesById) {
696
813
  exercises: exercises.filter(isRecord).map((ex) => {
697
814
  const id = coerceInt(ex.id);
698
815
  const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
699
- return mergeExercise(slotValues(ex, false), performed, {
816
+ return mergeExercise(prescriptionSlots(ex, id !== null ? savedById.get(id) : void 0), performed, {
700
817
  exerciseId: coerceInt(ex.exercise_id),
701
818
  title: typeof ex.title === "string" ? ex.title : "",
702
819
  instruction: str(ex.instruction),
@@ -706,14 +823,18 @@ function mergePrescriptionBlock(set, performedById, notesById) {
706
823
  })
707
824
  };
708
825
  }
709
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
826
+ /**
827
+ * A block straight from the saved copy (athlete-added or personal work; no template row). Its
828
+ * unperformed slots are the prescription — a personal session's targets live only here — and its
829
+ * performed slots are what was logged.
830
+ */
710
831
  function mergeSavedBlock(set, exercises) {
711
832
  return {
712
833
  order: coerceInt(set.order) ?? 0,
713
834
  title: str(set.title),
714
835
  instruction: str(set.instruction),
715
836
  isTest: coerceInt(set.is_test) === 1,
716
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
837
+ exercises: exercises.map((ex) => mergeExercise(prescriptionSlots(void 0, ex), slotValues(ex, true), {
717
838
  exerciseId: coerceInt(ex.exercise_id),
718
839
  title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
719
840
  instruction: str(ex.instruction),
@@ -736,8 +857,9 @@ function mergeAthleteWorkout(raw) {
736
857
  const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
737
858
  const logged = savedSets(saved);
738
859
  const performedById = performedSlotsByExerciseId(logged);
860
+ const savedById = savedRowsByTemplateId(logged);
739
861
  const notesById = notesByTemplateId(logged);
740
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
862
+ const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, savedById, notesById)).sort((a, b) => a.order - b.order);
741
863
  const prescribedIds = /* @__PURE__ */ new Set();
742
864
  for (const s of prescriptionSets) {
743
865
  const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
@@ -749,7 +871,7 @@ function mergeAthleteWorkout(raw) {
749
871
  }
750
872
  for (const { set, exercises } of logged) {
751
873
  const extra = exercises.filter((ex) => {
752
- if (slotValues(ex, true).size === 0) return false;
874
+ if (slotValues(ex, false).size === 0) return false;
753
875
  const id = coerceInt(ex.workout_set_exercise_id);
754
876
  return id === null || !prescribedIds.has(id);
755
877
  });
@@ -925,6 +1047,16 @@ function presentLogTargets(list) {
925
1047
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
926
1048
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
927
1049
  if (!saved) continue;
1050
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1051
+ const templatesById = /* @__PURE__ */ new Map();
1052
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1053
+ if (!isRecord(tSet)) continue;
1054
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
1055
+ for (const tEx of tExs) {
1056
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
1057
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
1058
+ }
1059
+ }
928
1060
  const date = str(rec.date) ?? "";
929
1061
  const workoutTitle = str(rec.workout_title) ?? "";
930
1062
  const program = str(rec.program_title);
@@ -939,12 +1071,14 @@ function presentLogTargets(list) {
939
1071
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
940
1072
  const id = coerceInt(ex.id);
941
1073
  if (id === null) return null;
1074
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1075
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
942
1076
  return {
943
1077
  savedWorkoutSetExerciseId: id,
944
1078
  title: exerciseTitle(ex),
945
1079
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
946
1080
  notes: str(ex.notes),
947
- prescribed: prescribedStrings(ex),
1081
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
948
1082
  performed: performedStrings(ex)
949
1083
  };
950
1084
  }).filter((e) => e !== null);
@@ -1069,6 +1203,28 @@ function presentExerciseHistory(detail) {
1069
1203
  };
1070
1204
  }
1071
1205
  //#endregion
1206
+ //#region src/exercise-history.ts
1207
+ /**
1208
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1209
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
1210
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
1211
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
1212
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
1213
+ */
1214
+ function historyInRange(presented, since, until) {
1215
+ if (since === void 0 && until === void 0) return presented;
1216
+ const sessions = presented.sessions.filter((s) => {
1217
+ const d = (s.date ?? "").slice(0, 10);
1218
+ if (since !== void 0 && d < since) return false;
1219
+ if (until !== void 0 && d > until) return false;
1220
+ return true;
1221
+ });
1222
+ return {
1223
+ ...presented,
1224
+ sessions
1225
+ };
1226
+ }
1227
+ //#endregion
1072
1228
  //#region src/coach-athlete-calendar.ts
1073
1229
  async function getArray(client, path, label) {
1074
1230
  const res = await client.request("GET", path);
@@ -1203,6 +1359,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1203
1359
  }
1204
1360
  //#endregion
1205
1361
  //#region src/athlete-set-write.ts
1362
+ const WRITE_CONCURRENCY = 4;
1206
1363
  /**
1207
1364
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1208
1365
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -1444,6 +1601,41 @@ async function swapAthleteExercise(client, args) {
1444
1601
  originalTeamExerciseId: coerceInt(template.exercise_id)
1445
1602
  };
1446
1603
  }
1604
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
1605
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1606
+ assertUniqueExerciseResults(results);
1607
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1608
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1609
+ return {
1610
+ savedWorkoutSetId,
1611
+ exercises,
1612
+ rawSet,
1613
+ suffix,
1614
+ extra,
1615
+ writes: results.map((result) => {
1616
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
1617
+ if (!ex) {
1618
+ const valid = exercises.map((candidate) => {
1619
+ const id = coerceInt(candidate.id);
1620
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
1621
+ }).filter((label) => label !== null);
1622
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1623
+ }
1624
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1625
+ 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.`);
1626
+ return {
1627
+ id: result.savedWorkoutSetExerciseId,
1628
+ body: {
1629
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1630
+ ...extra
1631
+ }
1632
+ };
1633
+ })
1634
+ };
1635
+ }
1636
+ function errorMessage(error) {
1637
+ return error instanceof Error ? error.message : String(error);
1638
+ }
1447
1639
  /**
1448
1640
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
1449
1641
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -1457,36 +1649,40 @@ async function swapAthleteExercise(client, args) {
1457
1649
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
1458
1650
  * open.
1459
1651
  */
1460
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1461
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1462
- assertUniqueExerciseResults(results);
1463
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1464
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1465
- let exercisesWritten = 0;
1466
- const projectedCompletion = /* @__PURE__ */ new Map();
1467
- for (const result of results) {
1468
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1469
- if (!ex) {
1470
- const valid = exercises.map((e) => {
1471
- const id = coerceInt(e.id);
1472
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
1473
- }).filter((x) => x !== null);
1474
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1475
- }
1476
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1477
- 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.`);
1478
- const body = {
1479
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
1480
- ...extra
1652
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
1653
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
1654
+ const put = (path, body, failureMessage, finalizer = false) => {
1655
+ const request = async () => {
1656
+ try {
1657
+ const res = await client.request("PUT", path, { body });
1658
+ if (!res.ok) throw new Error(failureMessage(res.status));
1659
+ } catch (error) {
1660
+ limit.cancel(error);
1661
+ throw error;
1662
+ }
1481
1663
  };
1482
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1483
- if (!res.ok) {
1484
- 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.` : "";
1485
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1486
- }
1487
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
1488
- exercisesWritten += 1;
1664
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
1665
+ };
1666
+ const confirmed = [];
1667
+ try {
1668
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
1669
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
1670
+ return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
1671
+ });
1672
+ confirmed.push(id);
1673
+ if (sessionProgress) {
1674
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
1675
+ sessionConfirmed.push(id);
1676
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
1677
+ }
1678
+ });
1679
+ } catch (error) {
1680
+ if (sessionProgress || confirmed.length === 0) throw error;
1681
+ confirmed.sort((a, b) => a - b);
1682
+ throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
1489
1683
  }
1684
+ const exercisesWritten = writes.length;
1685
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
1490
1686
  let setCompleted = false;
1491
1687
  if (mode === "log") {
1492
1688
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -1494,8 +1690,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1494
1690
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1495
1691
  ...extra
1496
1692
  };
1497
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1498
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1693
+ try {
1694
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
1695
+ } catch (error) {
1696
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
1697
+ }
1499
1698
  setCompleted = true;
1500
1699
  }
1501
1700
  }
@@ -1505,6 +1704,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1505
1704
  setCompleted
1506
1705
  };
1507
1706
  }
1707
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
1708
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
1709
+ }
1508
1710
  /**
1509
1711
  * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
1510
1712
  * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
@@ -1677,7 +1879,7 @@ function prescribedExerciseLabels(workouts) {
1677
1879
  return labels;
1678
1880
  }
1679
1881
  /** Group resolved exercises by saved set and write each set via the given log target. */
1680
- async function logResolvedExercises(client, target, workouts, resolved) {
1882
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
1681
1883
  const bySet = /* @__PURE__ */ new Map();
1682
1884
  for (const r of resolved) {
1683
1885
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -1687,15 +1889,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
1687
1889
  });
1688
1890
  bySet.set(r.savedWorkoutSetId, list);
1689
1891
  }
1690
- const out = [];
1691
- for (const [savedWorkoutSetId, results] of bySet) {
1692
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
1693
- out.push({
1694
- savedWorkoutSetId: written.savedWorkoutSetId,
1695
- exercisesLogged: written.exercisesWritten
1892
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
1893
+ const limit = createLimiter(WRITE_CONCURRENCY);
1894
+ const confirmedBySet = /* @__PURE__ */ new Map();
1895
+ const succeeded = [];
1896
+ try {
1897
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
1898
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
1899
+ succeeded.push(written.savedWorkoutSetId);
1900
+ return {
1901
+ savedWorkoutSetId: written.savedWorkoutSetId,
1902
+ exercisesLogged: written.exercisesWritten
1903
+ };
1696
1904
  });
1905
+ } catch (error) {
1906
+ const completed = new Set(succeeded);
1907
+ const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
1908
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
1909
+ succeeded.sort((a, b) => a - b);
1910
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
1911
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
1912
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
1697
1913
  }
1698
- return out;
1699
1914
  }
1700
1915
  /**
1701
1916
  * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
@@ -1768,7 +1983,7 @@ async function logSessionForAthlete(client, args) {
1768
1983
  const sets = await logResolvedExercises(client, {
1769
1984
  role: "coach",
1770
1985
  athleteId: args.athleteId
1771
- }, day, resolved);
1986
+ }, day, resolved, "Retry the same request to reconcile them.");
1772
1987
  return {
1773
1988
  date: args.date,
1774
1989
  created: false,
@@ -2062,9 +2277,75 @@ function repsList(ex) {
2062
2277
  const reps = ex.reps;
2063
2278
  if (Array.isArray(reps)) return reps.map((r) => String(r));
2064
2279
  if (reps === void 0 || reps === null) return [];
2065
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2280
+ const sets = Array.isArray(ex.weight) ? ex.weight.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2066
2281
  return Array.from({ length: sets }, () => String(reps));
2067
2282
  }
2283
+ /** Number of sets that the encoder will write for an exercise. */
2284
+ function exerciseSetCount(ex) {
2285
+ if (Array.isArray(ex.reps) && ex.reps.length > 0) return ex.reps.length;
2286
+ if (Array.isArray(ex.weight)) return ex.weight.length;
2287
+ if (!Array.isArray(ex.reps) && ex.reps !== void 0 && ex.reps !== null || ex.weight !== void 0 && ex.weight !== null) return Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2288
+ return 0;
2289
+ }
2290
+ function findSetSplits(blocks) {
2291
+ return blocks.flatMap((block) => block.exercises.flatMap((exercise) => {
2292
+ const setCount = exerciseSetCount(exercise);
2293
+ if (setCount <= 10) return [];
2294
+ return [{
2295
+ blockTitle: block.title,
2296
+ exerciseTitle: exercise.title ?? String(exercise.id),
2297
+ setCount,
2298
+ blockCount: Math.ceil(setCount / 10)
2299
+ }];
2300
+ }));
2301
+ }
2302
+ function setSplitSummary(blocks) {
2303
+ const splits = findSetSplits(blocks);
2304
+ if (splits.length === 0) return null;
2305
+ return `TrainHeroic supports at most 10 sets per exercise block. The following will be split into consecutive same-titled blocks: ${splits.map(({ blockTitle, exerciseTitle, setCount, blockCount }) => `${blockTitle} / ${exerciseTitle}: ${setCount} sets into ${blockCount} blocks`).join("; ")}.`;
2306
+ }
2307
+ function sliceExercise(exercise, setCount, start) {
2308
+ if (start > 0 && setCount <= start) return null;
2309
+ const chunkCount = setCount === 0 ? 0 : Math.min(10, Math.max(0, setCount - start));
2310
+ const chunk = { ...exercise };
2311
+ const hasPerSetReps = Array.isArray(exercise.reps) && exercise.reps.length > 0;
2312
+ const hasScalarReps = !Array.isArray(exercise.reps) && exercise.reps !== void 0 && exercise.reps !== null;
2313
+ if (Array.isArray(exercise.reps) && exercise.reps.length > 0) {
2314
+ chunk.reps = exercise.reps.slice(start, start + 10);
2315
+ delete chunk.sets;
2316
+ } else if (hasScalarReps) chunk.sets = chunkCount;
2317
+ if (Array.isArray(exercise.weight)) {
2318
+ chunk.weight = exercise.weight.slice(start, start + 10);
2319
+ if (!hasPerSetReps && !hasScalarReps) delete chunk.sets;
2320
+ } else if (!hasPerSetReps && exercise.weight !== void 0 && exercise.weight !== null) chunk.sets = chunkCount;
2321
+ return chunk;
2322
+ }
2323
+ /**
2324
+ * Split blocks so no encoded exercise exceeds TrainHeroic's ten parameter slots.
2325
+ * Exercises in a superset stay aligned by set range; shorter exercises appear only in
2326
+ * chunks where they still have sets.
2327
+ */
2328
+ function splitOversizedBlocks(blocks) {
2329
+ return blocks.flatMap((block) => {
2330
+ const setCounts = block.exercises.map(exerciseSetCount);
2331
+ const largestSetCount = Math.max(0, ...setCounts);
2332
+ const chunkCount = Math.max(1, Math.ceil(largestSetCount / 10));
2333
+ if (chunkCount === 1) return [block];
2334
+ return Array.from({ length: chunkCount }, (_, index) => {
2335
+ const start = index * 10;
2336
+ const exercises = block.exercises.map((exercise, exerciseIndex) => sliceExercise(exercise, setCounts[exerciseIndex] ?? 0, start)).filter((exercise) => exercise !== null);
2337
+ if (index === 0) return {
2338
+ ...block,
2339
+ exercises
2340
+ };
2341
+ return {
2342
+ title: block.title,
2343
+ ...block.type === void 0 ? {} : { type: block.type },
2344
+ exercises
2345
+ };
2346
+ });
2347
+ });
2348
+ }
2068
2349
  /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2069
2350
  function makeExercise(ex, workoutSetId, order, key) {
2070
2351
  const reps = repsList(ex);
@@ -2072,8 +2353,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2072
2353
  if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2073
2354
  const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2074
2355
  const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2075
- let count = reps.length;
2076
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2356
+ const count = exerciseSetCount(ex);
2077
2357
  let param2Type;
2078
2358
  let param2Values;
2079
2359
  if (hasWeight) {
@@ -2104,8 +2384,8 @@ function makeExercise(ex, workoutSetId, order, key) {
2104
2384
  eType: "e",
2105
2385
  use_count: 0
2106
2386
  };
2107
- const p1 = slots(reps);
2108
- const p2 = slots(param2Values);
2387
+ const p1 = slots(reps, 10);
2388
+ const p2 = slots(param2Values, 10);
2109
2389
  for (let i = 0; i < 10; i += 1) {
2110
2390
  entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2111
2391
  entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
@@ -2226,7 +2506,10 @@ function createPath(opts) {
2226
2506
  return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2227
2507
  }
2228
2508
  async function buildSession(client, opts) {
2229
- const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2509
+ const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
2510
+ const splitSummary = setSplitSummary(validatedBlocks);
2511
+ if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
2512
+ const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
2230
2513
  const sess = await req(client, "POST", createPath(opts), {});
2231
2514
  checkResponse(sessionCreateResponseSchema, sess, "session create");
2232
2515
  const workoutId = Number(sess.workout_id);
@@ -2289,7 +2572,7 @@ async function readSession(client, programId, date, pwId) {
2289
2572
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2290
2573
  return {
2291
2574
  pwId,
2292
- date: `${str$1(pw.year)}-${str$1(pw.month)}-${str$1(pw.day)}`,
2575
+ date: `${str$1(pw.year)}-${str$1(pw.month).padStart(2, "0")}-${str$1(pw.day).padStart(2, "0")}`,
2293
2576
  published: pw.published,
2294
2577
  instruction: str$1(pw.instruction),
2295
2578
  blocks
@@ -2309,14 +2592,13 @@ function readBlock(b) {
2309
2592
  };
2310
2593
  }
2311
2594
  function readExercise(ex) {
2312
- const reps = [];
2313
- const load = [];
2314
- for (let i = 1; i <= 10; i += 1) {
2315
- const r = str$1(ex[`param_1_data_${i}`]);
2316
- if (r !== "") reps.push(r);
2317
- const w = str$1(ex[`param_2_data_${i}`]);
2318
- if (w !== "") load.push(w);
2319
- }
2595
+ let last = 0;
2596
+ for (let i = 1; i <= 10; i += 1) if (str$1(ex[`param_1_data_${i}`]) !== "" || str$1(ex[`param_2_data_${i}`]) !== "") last = i;
2597
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
2598
+ const repsRaw = slots.map((i) => str$1(ex[`param_1_data_${i}`]));
2599
+ const loadRaw = slots.map((i) => str$1(ex[`param_2_data_${i}`]));
2600
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
2601
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
2320
2602
  return {
2321
2603
  order: Number(ex.order),
2322
2604
  title: str$1(ex.title),
@@ -2893,8 +3175,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2893
3175
  } catch {
2894
3176
  workouts = [];
2895
3177
  }
2896
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2897
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
3178
+ for (const ex of performedExercises(workouts)) {
2898
3179
  const family = classifyMainLift(ex.title);
2899
3180
  if (family === null) continue;
2900
3181
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3139,6 +3420,7 @@ var ExerciseLibrary = class {
3139
3420
  #byId = /* @__PURE__ */ new Map();
3140
3421
  #loaded = false;
3141
3422
  #fetchedAt = 0;
3423
+ #loading = null;
3142
3424
  constructor(client, cache = new MemoryLibraryCache()) {
3143
3425
  this.#client = client;
3144
3426
  this.#cache = cache;
@@ -3166,8 +3448,11 @@ var ExerciseLibrary = class {
3166
3448
  });
3167
3449
  }
3168
3450
  async ensureFresh() {
3169
- if (!this.#loaded) await this.#ensureLoaded();
3170
- else if (Date.now() - this.#fetchedAt > TTL_MS) await this.refresh();
3451
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS) return;
3452
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
3453
+ this.#loading = null;
3454
+ });
3455
+ await this.#loading;
3171
3456
  }
3172
3457
  async refresh() {
3173
3458
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -3186,6 +3471,7 @@ var ExerciseLibrary = class {
3186
3471
  return presentExercise(s.raw);
3187
3472
  }
3188
3473
  async defaultsMany(ids) {
3474
+ await this.ensureFresh();
3189
3475
  const result = /* @__PURE__ */ new Map();
3190
3476
  for (const id of ids) {
3191
3477
  const s = this.#byId.get(id);
@@ -3273,4 +3559,4 @@ var ExerciseLibrary = class {
3273
3559
  }
3274
3560
  };
3275
3561
  //#endregion
3276
- 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, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, sortRosterByRecency, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
3562
+ 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, PROGRAM_KINDS, SESSION_TEMPLATES_LIST_PATH, TrainHeroicAuthError, TrainHeroicClient, TrainHeroicHttpError, addExercisesToWorkout, analyticsMetricCatalog, asExerciseList, buildBlockPayload, buildCommentPayload, buildExerciseSetPayload, buildSearchText, buildSession, buildSetCompletePayload, calendarWriteError, checkResponse, chunk, classifyMainLift, coerceInt, coerceNum, collectAdvisories, copySession, createLimiter, createPersonalWorkout, createProgram, createSessionTemplate, dateWindows, defaultBlockType, definedProps, deleteComment, deleteProgram, exerciseSetCount, exerciseTitle, exerciseUnits, fetchAthleteCircuits, fetchAthleteMainLiftPRs, fetchAthletePrefs, fetchAthleteProfileSummary, fetchAthleteProgrammingPrograms, fetchAthleteUser, fetchAthleteWorkouts, fetchAthleteWorkoutsChunked, fetchCoachAthleteCalendar, fetchCoachAthleteCalendarSummary, fetchCoachAthleteWorkouts, fetchCoachRoster, fetchExerciseHistoryDetail, fetchExerciseHistoryList, fetchExerciseStats, fetchLeaderboard, fetchPersonalRecords, fetchRecentExercises, fetchRosterActivity, fetchRosterMainLiftPRs, fetchStreams, fetchTeamAthleteIds, fetchWorkingMaxes, findSavedWorkoutSet, findSetSplits, historyInRange, inviteAthletes, isPersonalSession, isRecord, logAdHocSession, logAthleteSet, logForAthlete, logSessionForAthlete, loginTrainHeroic, makeExercise, mapPool, mergeWorkoutsById, performedExercises, prescribeAthleteSet, prescribeForAthlete, presentAthleteWorkout, presentAthleteWorkoutExport, presentAthleteWorkouts, presentAthleteWorkoutsExport, presentCoachAthleteTraining, presentExercise, presentExerciseHistory, presentLogTargets, programWorkoutOnDate, publishSession, queryAnalytics, rankSearch, readLive, readSession, removePersonalWorkout, removeSession, repsList, resolveAthleteMainLifts, resolveAthleteUserId, resolveBuildProgramId, resolveLeaderboard, savedWorkoutOf, searchExerciseHistory, selectWorkouts, selectWorkoutsByProgram, sendComment, serializeWorkoutHistory, setAthleteExerciseNote, setAthleteWorkoutNote, setSessionInstruction, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, str, summarizeAthleteWorkouts, swapAthleteExercise, teamPublishTarget, teamVolume, toSetResults, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "3.5.0",
3
+ "version": "3.5.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,8 +26,9 @@
26
26
  "dist"
27
27
  ],
28
28
  "dependencies": {
29
+ "es-toolkit": "^1.52.0",
29
30
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "3.5.0"
31
+ "@trainheroic-unofficial/dto": "3.5.2"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@types/node": "^26.3.0",