@trainheroic-unofficial/js 3.5.1 → 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 +43 -3
- package/dist/index.mjs +323 -105
- package/package.json +3 -2
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
|
-
/**
|
|
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
|
|
@@ -1125,4 +1165,4 @@ declare class ExerciseLibrary implements ExerciseIndex {
|
|
|
1125
1165
|
stats(): Promise<Record<string, unknown>>;
|
|
1126
1166
|
}
|
|
1127
1167
|
//#endregion
|
|
1128
|
-
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, 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, 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, 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, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, 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
|
-
|
|
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
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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(
|
|
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
|
-
/**
|
|
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(
|
|
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,
|
|
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:
|
|
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
|
|
1461
|
-
const { exercises, rawSet } =
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
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
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
}
|
|
1487
|
-
|
|
1488
|
-
|
|
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
|
-
|
|
1498
|
-
|
|
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
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
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,
|
|
@@ -2357,7 +2572,7 @@ async function readSession(client, programId, date, pwId) {
|
|
|
2357
2572
|
const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
|
|
2358
2573
|
return {
|
|
2359
2574
|
pwId,
|
|
2360
|
-
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")}`,
|
|
2361
2576
|
published: pw.published,
|
|
2362
2577
|
instruction: str$1(pw.instruction),
|
|
2363
2578
|
blocks
|
|
@@ -2377,14 +2592,13 @@ function readBlock(b) {
|
|
|
2377
2592
|
};
|
|
2378
2593
|
}
|
|
2379
2594
|
function readExercise(ex) {
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
}
|
|
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 : [];
|
|
2388
2602
|
return {
|
|
2389
2603
|
order: Number(ex.order),
|
|
2390
2604
|
title: str$1(ex.title),
|
|
@@ -2961,8 +3175,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
|
2961
3175
|
} catch {
|
|
2962
3176
|
workouts = [];
|
|
2963
3177
|
}
|
|
2964
|
-
for (const
|
|
2965
|
-
if (ex.performed.length === 0 || ex.exerciseId === null) continue;
|
|
3178
|
+
for (const ex of performedExercises(workouts)) {
|
|
2966
3179
|
const family = classifyMainLift(ex.title);
|
|
2967
3180
|
if (family === null) continue;
|
|
2968
3181
|
const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
|
|
@@ -3207,6 +3420,7 @@ var ExerciseLibrary = class {
|
|
|
3207
3420
|
#byId = /* @__PURE__ */ new Map();
|
|
3208
3421
|
#loaded = false;
|
|
3209
3422
|
#fetchedAt = 0;
|
|
3423
|
+
#loading = null;
|
|
3210
3424
|
constructor(client, cache = new MemoryLibraryCache()) {
|
|
3211
3425
|
this.#client = client;
|
|
3212
3426
|
this.#cache = cache;
|
|
@@ -3234,8 +3448,11 @@ var ExerciseLibrary = class {
|
|
|
3234
3448
|
});
|
|
3235
3449
|
}
|
|
3236
3450
|
async ensureFresh() {
|
|
3237
|
-
if (
|
|
3238
|
-
|
|
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;
|
|
3239
3456
|
}
|
|
3240
3457
|
async refresh() {
|
|
3241
3458
|
const res = await this.#client.request("GET", LIBRARY_PATH);
|
|
@@ -3254,6 +3471,7 @@ var ExerciseLibrary = class {
|
|
|
3254
3471
|
return presentExercise(s.raw);
|
|
3255
3472
|
}
|
|
3256
3473
|
async defaultsMany(ids) {
|
|
3474
|
+
await this.ensureFresh();
|
|
3257
3475
|
const result = /* @__PURE__ */ new Map();
|
|
3258
3476
|
for (const id of ids) {
|
|
3259
3477
|
const s = this.#byId.get(id);
|
|
@@ -3341,4 +3559,4 @@ var ExerciseLibrary = class {
|
|
|
3341
3559
|
}
|
|
3342
3560
|
};
|
|
3343
3561
|
//#endregion
|
|
3344
|
-
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, 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, 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, setSplitSummary, sortRosterByRecency, splitOversizedBlocks, 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.
|
|
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.
|
|
31
|
+
"@trainheroic-unofficial/dto": "3.5.2"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@types/node": "^26.3.0",
|