@trainheroic-unofficial/cli 3.6.0 → 3.7.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/cli.mjs
CHANGED
|
@@ -440,11 +440,37 @@ z.object({
|
|
|
440
440
|
match: exerciseViewSchema.nullable(),
|
|
441
441
|
candidates: z.array(exerciseViewSchema)
|
|
442
442
|
});
|
|
443
|
+
/** TrainHeroic's documented exercise parameter-type codes. */
|
|
444
|
+
const exerciseParamTypeSchema = z.union([
|
|
445
|
+
z.literal(0),
|
|
446
|
+
z.literal(1),
|
|
447
|
+
z.literal(2),
|
|
448
|
+
z.literal(3),
|
|
449
|
+
z.literal(4),
|
|
450
|
+
z.literal(5),
|
|
451
|
+
z.literal(6),
|
|
452
|
+
z.literal(7),
|
|
453
|
+
z.literal(10),
|
|
454
|
+
z.literal(11),
|
|
455
|
+
z.literal(12),
|
|
456
|
+
z.literal(13),
|
|
457
|
+
z.literal(14),
|
|
458
|
+
z.literal(18)
|
|
459
|
+
]);
|
|
460
|
+
const exerciseWriteShape = {
|
|
461
|
+
title: z.string().trim().min(1),
|
|
462
|
+
param_1_type: exerciseParamTypeSchema.optional(),
|
|
463
|
+
param_2_type: exerciseParamTypeSchema.optional()
|
|
464
|
+
};
|
|
443
465
|
/** Body for creating a custom exercise; extra fields the API accepts are preserved. */
|
|
444
466
|
const exerciseCreateSchema = z.looseObject({
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
467
|
+
...exerciseWriteShape,
|
|
468
|
+
points_of_performance: z.string().default("")
|
|
469
|
+
});
|
|
470
|
+
/** Body for updating a custom exercise without clearing fields the caller omitted. */
|
|
471
|
+
const exerciseUpdateSchema = z.looseObject({
|
|
472
|
+
...exerciseWriteShape,
|
|
473
|
+
points_of_performance: z.string().optional()
|
|
448
474
|
});
|
|
449
475
|
z.object({
|
|
450
476
|
streamId: idSchema,
|
|
@@ -784,12 +810,47 @@ const sessionTemplateCreateSchema = z.object({
|
|
|
784
810
|
instruction: z.string().optional()
|
|
785
811
|
});
|
|
786
812
|
//#endregion
|
|
813
|
+
//#region ../js/src/date-window.ts
|
|
814
|
+
const DAY_MS = 864e5;
|
|
815
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
816
|
+
const MAX_DATE_WINDOWS = 100;
|
|
817
|
+
function dayNumber(value) {
|
|
818
|
+
if (!ISO_DAY.test(value)) return null;
|
|
819
|
+
const timestamp = Date.parse(`${value}T00:00:00Z`);
|
|
820
|
+
if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) return null;
|
|
821
|
+
return timestamp / DAY_MS;
|
|
822
|
+
}
|
|
823
|
+
function isoDay$1(day) {
|
|
824
|
+
return (/* @__PURE__ */ new Date(day * DAY_MS)).toISOString().slice(0, 10);
|
|
825
|
+
}
|
|
826
|
+
/** Number of calendar days in an inclusive ISO-date range, or null for an invalid range. */
|
|
827
|
+
function dateSpanDays(start, end) {
|
|
828
|
+
const first = dayNumber(start);
|
|
829
|
+
const last = dayNumber(end);
|
|
830
|
+
return first === null || last === null || first > last ? null : last - first + 1;
|
|
831
|
+
}
|
|
832
|
+
/** Split an inclusive ISO-date range into at most 100 ordered, non-overlapping windows. */
|
|
833
|
+
function splitDateRange(start, end, maxDays) {
|
|
834
|
+
const first = dayNumber(start);
|
|
835
|
+
const last = dayNumber(end);
|
|
836
|
+
if (first === null || last === null || first > last) return null;
|
|
837
|
+
if (!Number.isSafeInteger(maxDays) || maxDays < 1) throw new RangeError("maxDays must be a positive integer.");
|
|
838
|
+
if (Math.ceil((last - first + 1) / maxDays) > MAX_DATE_WINDOWS) throw new RangeError(`Date range is limited to ${MAX_DATE_WINDOWS} windows; narrow the range or increase the window size.`);
|
|
839
|
+
const windows = [];
|
|
840
|
+
for (let cursor = first; cursor <= last; cursor += maxDays) windows.push({
|
|
841
|
+
start: isoDay$1(cursor),
|
|
842
|
+
end: isoDay$1(Math.min(cursor + maxDays - 1, last))
|
|
843
|
+
});
|
|
844
|
+
return windows;
|
|
845
|
+
}
|
|
846
|
+
//#endregion
|
|
787
847
|
//#region ../js/src/http-error.ts
|
|
788
848
|
const MAX_REQUEST_KEYS = 50;
|
|
789
849
|
const MAX_RESPONSE_DEPTH = 4;
|
|
790
850
|
const MAX_RESPONSE_KEYS = 20;
|
|
791
851
|
const MAX_RESPONSE_ITEMS = 10;
|
|
792
852
|
const MAX_RESPONSE_NODES = 50;
|
|
853
|
+
const MAX_RESPONSE_STRING = 2e3;
|
|
793
854
|
const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
|
|
794
855
|
"code",
|
|
795
856
|
"detail",
|
|
@@ -827,6 +888,11 @@ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
|
|
|
827
888
|
14,
|
|
828
889
|
18
|
|
829
890
|
]);
|
|
891
|
+
/** Keep provider diagnostics useful while removing common credentials and direct identifiers. */
|
|
892
|
+
function redactText(value) {
|
|
893
|
+
const redacted = value.slice(0, MAX_RESPONSE_STRING).replace(/\bAuthorization(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&]+)/giu, (_match, separator) => `Authorization${separator}[Redacted]`).replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/giu, "Bearer [Redacted]").replace(/\b(password|passwd|secret|token|access[_-]?token|refresh[_-]?token|session(?:[_-]?(?:id|token))?|api[_-]?key|client[_-]?secret)(["']?\s*[:=]\s*)(?:"(?:\\(?:[\s\S]|$)|[^"\\])*(?:"|$)|'(?:\\(?:[\s\S]|$)|[^'\\])*(?:'|$)|[^"'\r\n,;&}\]]+)/giu, (_match, key, separator) => `${key}${separator}[Redacted]`).replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu, "[Redacted email]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/gu, "[Redacted IP]").replace(/\b\d{3}-\d{2}-\d{4}\b/gu, "[Redacted]").replace(/\b(?:bearer\s+)?[a-f0-9]{32,}\b/giu, "[Redacted]");
|
|
894
|
+
return value.length <= MAX_RESPONSE_STRING ? redacted : `${redacted}…[truncated]`;
|
|
895
|
+
}
|
|
830
896
|
function safeFieldName(key) {
|
|
831
897
|
if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
|
|
832
898
|
if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
|
|
@@ -854,17 +920,22 @@ function requestBodySummary(body) {
|
|
|
854
920
|
const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
|
|
855
921
|
const keys = entries.map(([key]) => safeFieldName(key));
|
|
856
922
|
const values = {};
|
|
923
|
+
const arrayLengths = {};
|
|
857
924
|
for (const [key, value] of entries) {
|
|
858
925
|
const safeValue = safeRequestValue(key, value);
|
|
859
926
|
if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
|
|
927
|
+
if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
|
|
860
928
|
}
|
|
861
|
-
|
|
929
|
+
const byKey = new Map(entries);
|
|
930
|
+
const dateStart = byKey.get("date_start");
|
|
931
|
+
const dateEnd = byKey.get("date_end");
|
|
932
|
+
const span = typeof dateStart === "string" && typeof dateEnd === "string" ? dateSpanDays(dateStart, dateEnd) : null;
|
|
933
|
+
return {
|
|
862
934
|
type: "object",
|
|
863
935
|
keys,
|
|
864
|
-
values
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
keys
|
|
936
|
+
...Object.keys(values).length > 0 ? { values } : {},
|
|
937
|
+
...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
|
|
938
|
+
...span === null ? {} : { dateSpanDays: span }
|
|
868
939
|
};
|
|
869
940
|
}
|
|
870
941
|
const primitive = typeof body;
|
|
@@ -876,7 +947,7 @@ function sanitizedDiagnosticValue(value, depth, budget, field) {
|
|
|
876
947
|
if (value === null) return null;
|
|
877
948
|
if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
|
|
878
949
|
if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
|
|
879
|
-
if (typeof value === "string") return
|
|
950
|
+
if (typeof value === "string") return redactText(value);
|
|
880
951
|
if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
|
|
881
952
|
if (Array.isArray(value)) {
|
|
882
953
|
const result = [];
|
|
@@ -955,6 +1026,12 @@ function safeResponseBodyDiagnostics(body) {
|
|
|
955
1026
|
return "[Unavailable]";
|
|
956
1027
|
}
|
|
957
1028
|
}
|
|
1029
|
+
/** Format a bounded provider diagnostic for an in-band tool or SDK error. */
|
|
1030
|
+
function trainHeroicApiErrorMessage(label, status, responseBody) {
|
|
1031
|
+
const diagnostic = safeResponseBodyDiagnostics(responseBody);
|
|
1032
|
+
const detail = diagnostic && typeof diagnostic === "object" && !Array.isArray(diagnostic) ? typeof diagnostic.message === "string" ? diagnostic.message : JSON.stringify(diagnostic) : typeof diagnostic === "string" ? diagnostic : JSON.stringify(diagnostic);
|
|
1033
|
+
return detail && detail !== "{\"type\":\"object\"}" ? `${label} failed (HTTP ${status}): ${detail}` : `${label} failed (HTTP ${status}).`;
|
|
1034
|
+
}
|
|
958
1035
|
/** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
|
|
959
1036
|
var TrainHeroicHttpError = class extends Error {
|
|
960
1037
|
name = "TrainHeroicHttpError";
|
|
@@ -982,6 +1059,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
|
|
|
982
1059
|
} catch {}
|
|
983
1060
|
}
|
|
984
1061
|
//#endregion
|
|
1062
|
+
//#region ../js/src/transport.ts
|
|
1063
|
+
const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
|
|
1064
|
+
//#endregion
|
|
985
1065
|
//#region ../js/src/auth.ts
|
|
986
1066
|
const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
|
|
987
1067
|
/**
|
|
@@ -1005,7 +1085,7 @@ function authUrl() {
|
|
|
1005
1085
|
*/
|
|
1006
1086
|
async function loginTrainHeroic(email, password, options = {}) {
|
|
1007
1087
|
const url = authUrl();
|
|
1008
|
-
const res = await
|
|
1088
|
+
const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
|
|
1009
1089
|
method: "POST",
|
|
1010
1090
|
headers: {
|
|
1011
1091
|
"content-type": "application/x-www-form-urlencoded",
|
|
@@ -1017,6 +1097,7 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
1017
1097
|
}).toString()
|
|
1018
1098
|
});
|
|
1019
1099
|
if (!res.ok) {
|
|
1100
|
+
await res.body?.cancel().catch(() => {});
|
|
1020
1101
|
notifyHttpError(options.onHttpError, "POST", url, res.status);
|
|
1021
1102
|
return null;
|
|
1022
1103
|
}
|
|
@@ -1030,127 +1111,40 @@ async function loginTrainHeroic(email, password, options = {}) {
|
|
|
1030
1111
|
};
|
|
1031
1112
|
}
|
|
1032
1113
|
//#endregion
|
|
1033
|
-
//#region
|
|
1034
|
-
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
1035
|
-
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
1114
|
+
//#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
|
|
1036
1115
|
/**
|
|
1037
|
-
*
|
|
1038
|
-
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
1039
|
-
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
1040
|
-
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
1041
|
-
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
1042
|
-
*/
|
|
1043
|
-
function envBase(key, fallback) {
|
|
1044
|
-
const v = (globalThis.process?.env)?.[key];
|
|
1045
|
-
return v && v.length > 0 ? v : fallback;
|
|
1046
|
-
}
|
|
1047
|
-
var TrainHeroicAuthError = class extends Error {
|
|
1048
|
-
name = "TrainHeroicAuthError";
|
|
1049
|
-
};
|
|
1050
|
-
/**
|
|
1051
|
-
* Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
|
|
1052
|
-
* grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
|
|
1053
|
-
* *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
|
|
1054
|
-
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
1116
|
+
* Splits an array into smaller arrays of a specified length.
|
|
1055
1117
|
*
|
|
1056
|
-
*
|
|
1057
|
-
*
|
|
1058
|
-
*
|
|
1059
|
-
*
|
|
1118
|
+
* This function takes an input array and divides it into multiple smaller arrays,
|
|
1119
|
+
* each of a specified length. If the input array cannot be evenly divided,
|
|
1120
|
+
* the final sub-array will contain the remaining elements.
|
|
1121
|
+
*
|
|
1122
|
+
* @template T The type of elements in the array.
|
|
1123
|
+
* @param arr - The array to be chunked into smaller arrays.
|
|
1124
|
+
* @param size - The size of each smaller array. Must be a positive integer.
|
|
1125
|
+
* @returns A two-dimensional array where each sub-array has a maximum length of `size`.
|
|
1126
|
+
* @throws {Error} Throws an error if `size` is not a positive integer.
|
|
1127
|
+
*
|
|
1128
|
+
* @example
|
|
1129
|
+
* // Splits an array of numbers into sub-arrays of length 2
|
|
1130
|
+
* chunk([1, 2, 3, 4, 5], 2);
|
|
1131
|
+
* // Returns: [[1, 2], [3, 4], [5]]
|
|
1132
|
+
*
|
|
1133
|
+
* @example
|
|
1134
|
+
* // Splits an array of strings into sub-arrays of length 3
|
|
1135
|
+
* chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 3);
|
|
1136
|
+
* // Returns: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
|
|
1060
1137
|
*/
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
this.#email = email;
|
|
1070
|
-
this.#password = password;
|
|
1071
|
-
this.#sessionId = sessionId;
|
|
1072
|
-
this.#onSession = options.onSession;
|
|
1073
|
-
this.#onHttpError = options.onHttpError;
|
|
1074
|
-
}
|
|
1075
|
-
get sessionId() {
|
|
1076
|
-
return this.#sessionId;
|
|
1077
|
-
}
|
|
1078
|
-
async #ensureSession() {
|
|
1079
|
-
if (this.#sessionId) return this.#sessionId;
|
|
1080
|
-
this.#loginInFlight ??= this.#login();
|
|
1081
|
-
try {
|
|
1082
|
-
return await this.#loginInFlight;
|
|
1083
|
-
} finally {
|
|
1084
|
-
this.#loginInFlight = null;
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
|
-
async #login() {
|
|
1088
|
-
const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
|
|
1089
|
-
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
1090
|
-
this.#sessionId = session.sessionId;
|
|
1091
|
-
try {
|
|
1092
|
-
this.#onSession?.(this.#sessionId);
|
|
1093
|
-
} catch {}
|
|
1094
|
-
return this.#sessionId;
|
|
1138
|
+
function chunk(arr, size) {
|
|
1139
|
+
if (!Number.isInteger(size) || size <= 0) throw new Error("Size must be an integer greater than zero.");
|
|
1140
|
+
const chunkLength = Math.ceil(arr.length / size);
|
|
1141
|
+
const result = Array(chunkLength);
|
|
1142
|
+
for (let index = 0; index < chunkLength; index++) {
|
|
1143
|
+
const start = index * size;
|
|
1144
|
+
const end = start + size;
|
|
1145
|
+
result[index] = arr.slice(start, end);
|
|
1095
1146
|
}
|
|
1096
|
-
|
|
1097
|
-
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
1098
|
-
let session = await this.#ensureSession();
|
|
1099
|
-
let res = await this.#send(method, url, session, options.body);
|
|
1100
|
-
if (res.status === 401 || res.status === 403) {
|
|
1101
|
-
if (this.#sessionId === session) this.#sessionId = null;
|
|
1102
|
-
session = await this.#ensureSession();
|
|
1103
|
-
res = await this.#send(method, url, session, options.body);
|
|
1104
|
-
}
|
|
1105
|
-
const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
|
|
1106
|
-
let text;
|
|
1107
|
-
try {
|
|
1108
|
-
text = await res.text();
|
|
1109
|
-
} catch (error) {
|
|
1110
|
-
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
|
|
1111
|
-
throw error;
|
|
1112
|
-
}
|
|
1113
|
-
const data = parseResponseText(text);
|
|
1114
|
-
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
|
|
1115
|
-
requestBody: options.body,
|
|
1116
|
-
responseBody: data
|
|
1117
|
-
});
|
|
1118
|
-
return {
|
|
1119
|
-
status: res.status,
|
|
1120
|
-
ok: res.ok,
|
|
1121
|
-
data
|
|
1122
|
-
};
|
|
1123
|
-
}
|
|
1124
|
-
#send(method, url, session, body) {
|
|
1125
|
-
const upper = method.toUpperCase();
|
|
1126
|
-
const headers = {
|
|
1127
|
-
accept: "application/json",
|
|
1128
|
-
"session-token": session
|
|
1129
|
-
};
|
|
1130
|
-
const init = {
|
|
1131
|
-
method: upper,
|
|
1132
|
-
headers
|
|
1133
|
-
};
|
|
1134
|
-
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
1135
|
-
headers["content-type"] = "application/json";
|
|
1136
|
-
init.body = JSON.stringify(body);
|
|
1137
|
-
}
|
|
1138
|
-
return fetch(url, init);
|
|
1139
|
-
}
|
|
1140
|
-
};
|
|
1141
|
-
//#endregion
|
|
1142
|
-
//#region ../js/src/response-check.ts
|
|
1143
|
-
/**
|
|
1144
|
-
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
1145
|
-
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
1146
|
-
* when TrainHeroic renames or drops a field we read.
|
|
1147
|
-
*/
|
|
1148
|
-
function checkResponse(schema, data, label) {
|
|
1149
|
-
const result = schema.safeParse(data);
|
|
1150
|
-
if (result.success) return;
|
|
1151
|
-
const issue = result.error.issues[0];
|
|
1152
|
-
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
1153
|
-
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
1147
|
+
return result;
|
|
1154
1148
|
}
|
|
1155
1149
|
//#endregion
|
|
1156
1150
|
//#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
|
|
@@ -1417,6 +1411,141 @@ function assertPositiveInteger(value, label) {
|
|
|
1417
1411
|
if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
|
|
1418
1412
|
}
|
|
1419
1413
|
//#endregion
|
|
1414
|
+
//#region ../js/src/client.ts
|
|
1415
|
+
const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
|
|
1416
|
+
const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
|
|
1417
|
+
const MAX_REQUEST_CONCURRENCY = 4;
|
|
1418
|
+
/**
|
|
1419
|
+
* Resolve an API host, allowing an env override. The override exists so a test harness can point
|
|
1420
|
+
* the client at a local fake backend (and it doubles as a staging knob); production leaves these
|
|
1421
|
+
* unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
|
|
1422
|
+
* — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
|
|
1423
|
+
* read per request (not at module load) so a value the harness sets in the child env always wins.
|
|
1424
|
+
*/
|
|
1425
|
+
function envBase(key, fallback) {
|
|
1426
|
+
const v = (globalThis.process?.env)?.[key];
|
|
1427
|
+
return v && v.length > 0 ? v : fallback;
|
|
1428
|
+
}
|
|
1429
|
+
var TrainHeroicAuthError = class extends Error {
|
|
1430
|
+
name = "TrainHeroicAuthError";
|
|
1431
|
+
};
|
|
1432
|
+
/**
|
|
1433
|
+
* Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
|
|
1434
|
+
* grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
|
|
1435
|
+
* *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
|
|
1436
|
+
* TrainHeroic has no refresh token and sessions expire after ~1-2h.
|
|
1437
|
+
*
|
|
1438
|
+
* Anything that wants a session to outlive one client owns that itself: pass a previously
|
|
1439
|
+
* acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
|
|
1440
|
+
* wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
|
|
1441
|
+
* invocation is a fresh process — because otherwise every operation replays the password.
|
|
1442
|
+
*/
|
|
1443
|
+
var TrainHeroicClient = class {
|
|
1444
|
+
#email;
|
|
1445
|
+
#password;
|
|
1446
|
+
#onSession;
|
|
1447
|
+
#onHttpError;
|
|
1448
|
+
#transport;
|
|
1449
|
+
#requestLimit = createLimiter(MAX_REQUEST_CONCURRENCY);
|
|
1450
|
+
#sessionId;
|
|
1451
|
+
#loginInFlight = null;
|
|
1452
|
+
constructor(email, password, sessionId = null, options = {}) {
|
|
1453
|
+
this.#email = email;
|
|
1454
|
+
this.#password = password;
|
|
1455
|
+
this.#sessionId = sessionId;
|
|
1456
|
+
this.#onSession = options.onSession;
|
|
1457
|
+
this.#onHttpError = options.onHttpError;
|
|
1458
|
+
this.#transport = options.transport ?? defaultTrainHeroicTransport;
|
|
1459
|
+
}
|
|
1460
|
+
get sessionId() {
|
|
1461
|
+
return this.#sessionId;
|
|
1462
|
+
}
|
|
1463
|
+
async #ensureSession() {
|
|
1464
|
+
if (this.#sessionId) return this.#sessionId;
|
|
1465
|
+
this.#loginInFlight ??= this.#login();
|
|
1466
|
+
try {
|
|
1467
|
+
return await this.#loginInFlight;
|
|
1468
|
+
} finally {
|
|
1469
|
+
this.#loginInFlight = null;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
async #login() {
|
|
1473
|
+
const session = await loginTrainHeroic(this.#email, this.#password, {
|
|
1474
|
+
...this.#onHttpError ? { onHttpError: this.#onHttpError } : {},
|
|
1475
|
+
transport: this.#transport
|
|
1476
|
+
});
|
|
1477
|
+
if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
|
|
1478
|
+
this.#sessionId = session.sessionId;
|
|
1479
|
+
try {
|
|
1480
|
+
this.#onSession?.(this.#sessionId);
|
|
1481
|
+
} catch {}
|
|
1482
|
+
return this.#sessionId;
|
|
1483
|
+
}
|
|
1484
|
+
async request(method, path, options = {}) {
|
|
1485
|
+
await this.#ensureSession();
|
|
1486
|
+
return this.#requestLimit.run(() => this.#request(method, path, options));
|
|
1487
|
+
}
|
|
1488
|
+
async #request(method, path, options) {
|
|
1489
|
+
const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
|
|
1490
|
+
let session = await this.#ensureSession();
|
|
1491
|
+
let res = await this.#send(method, url, session, options.body);
|
|
1492
|
+
if (res.status === 401 || res.status === 403) {
|
|
1493
|
+
await res.body?.cancel().catch(() => {});
|
|
1494
|
+
if (this.#sessionId === session) this.#sessionId = null;
|
|
1495
|
+
session = await this.#ensureSession();
|
|
1496
|
+
res = await this.#send(method, url, session, options.body);
|
|
1497
|
+
}
|
|
1498
|
+
const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
|
|
1499
|
+
let text;
|
|
1500
|
+
try {
|
|
1501
|
+
text = await res.text();
|
|
1502
|
+
} catch (error) {
|
|
1503
|
+
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
|
|
1504
|
+
throw error;
|
|
1505
|
+
}
|
|
1506
|
+
const data = parseResponseText(text);
|
|
1507
|
+
if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
|
|
1508
|
+
requestBody: options.body,
|
|
1509
|
+
responseBody: data
|
|
1510
|
+
});
|
|
1511
|
+
return {
|
|
1512
|
+
status: res.status,
|
|
1513
|
+
ok: res.ok,
|
|
1514
|
+
data
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
#send(method, url, session, body) {
|
|
1518
|
+
const upper = method.toUpperCase();
|
|
1519
|
+
const headers = {
|
|
1520
|
+
accept: "application/json",
|
|
1521
|
+
"session-token": session
|
|
1522
|
+
};
|
|
1523
|
+
const init = {
|
|
1524
|
+
method: upper,
|
|
1525
|
+
headers
|
|
1526
|
+
};
|
|
1527
|
+
if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
|
|
1528
|
+
headers["content-type"] = "application/json";
|
|
1529
|
+
init.body = JSON.stringify(body);
|
|
1530
|
+
}
|
|
1531
|
+
return this.#transport(url, init);
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
//#endregion
|
|
1535
|
+
//#region ../js/src/response-check.ts
|
|
1536
|
+
/**
|
|
1537
|
+
* Validate an API response against its (loose) expected shape and warn once on drift.
|
|
1538
|
+
* Never throws: callers keep working via defensive coercion. This only surfaces a signal
|
|
1539
|
+
* when TrainHeroic renames or drops a field we read.
|
|
1540
|
+
*/
|
|
1541
|
+
function checkResponse(schema, data, label) {
|
|
1542
|
+
const result = schema.safeParse(data);
|
|
1543
|
+
if (result.success) return;
|
|
1544
|
+
const issue = result.error.issues[0];
|
|
1545
|
+
const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
|
|
1546
|
+
console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
|
|
1547
|
+
}
|
|
1548
|
+
//#endregion
|
|
1420
1549
|
//#region ../js/src/athlete.ts
|
|
1421
1550
|
async function getJson(client, path, label) {
|
|
1422
1551
|
const res = await client.request("GET", path);
|
|
@@ -1544,27 +1673,9 @@ async function programWorkoutOnDate(client, date, programWorkoutId) {
|
|
|
1544
1673
|
if (target === void 0) throw new Error(`No workout with id ${programWorkoutId} on ${date}. Get the id and date from athlete_workouts.`);
|
|
1545
1674
|
return target;
|
|
1546
1675
|
}
|
|
1547
|
-
/**
|
|
1548
|
-
function shiftDate(iso, days) {
|
|
1549
|
-
const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
|
|
1550
|
-
d.setUTCDate(d.getUTCDate() + days);
|
|
1551
|
-
return d.toISOString().slice(0, 10);
|
|
1552
|
-
}
|
|
1553
|
-
/** Split an inclusive `[start, end]` range into consecutive non-overlapping windows of `windowDays`. */
|
|
1676
|
+
/** Split an inclusive range into at most 100 consecutive, non-overlapping windows. */
|
|
1554
1677
|
function dateWindows(startDate, endDate, windowDays) {
|
|
1555
|
-
|
|
1556
|
-
const windows = [];
|
|
1557
|
-
let cursor = startDate;
|
|
1558
|
-
while (cursor <= endDate) {
|
|
1559
|
-
const winEnd = shiftDate(cursor, size - 1);
|
|
1560
|
-
const clamped = winEnd > endDate ? endDate : winEnd;
|
|
1561
|
-
windows.push({
|
|
1562
|
-
start: cursor,
|
|
1563
|
-
end: clamped
|
|
1564
|
-
});
|
|
1565
|
-
cursor = shiftDate(clamped, 1);
|
|
1566
|
-
}
|
|
1567
|
-
return windows;
|
|
1678
|
+
return splitDateRange(startDate, endDate, Math.max(1, Math.floor(windowDays))) ?? [];
|
|
1568
1679
|
}
|
|
1569
1680
|
/**
|
|
1570
1681
|
* Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
|
|
@@ -3926,12 +4037,15 @@ const ANALYTICS_BODY_KEY = {
|
|
|
3926
4037
|
exerciseId: "exercise_id",
|
|
3927
4038
|
useMetric: "use_metric"
|
|
3928
4039
|
};
|
|
4040
|
+
const TRAINING_SUMMARY_USER_BATCH = 5;
|
|
4041
|
+
const TRAINING_SUMMARY_RANGE_DAYS = 90;
|
|
4042
|
+
const MAX_TRAINING_SUMMARY_REQUESTS = 100;
|
|
3929
4043
|
/**
|
|
3930
4044
|
* Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
|
|
3931
4045
|
* athlete metrics need one or more `userIds` (passed together — the report returns a row per
|
|
3932
4046
|
* athlete). Throws a readable Error when a required input is missing or the call fails.
|
|
3933
4047
|
*/
|
|
3934
|
-
async function
|
|
4048
|
+
async function requestAnalytics(client, args) {
|
|
3935
4049
|
const spec = ANALYTICS_METRICS[args.metric];
|
|
3936
4050
|
const body = {};
|
|
3937
4051
|
if (spec.scope === "team") {
|
|
@@ -3959,6 +4073,42 @@ async function queryAnalytics(client, args) {
|
|
|
3959
4073
|
if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
|
|
3960
4074
|
return res.data;
|
|
3961
4075
|
}
|
|
4076
|
+
function reportRows(report) {
|
|
4077
|
+
if (report === null || typeof report !== "object") return null;
|
|
4078
|
+
const rows = report.rows;
|
|
4079
|
+
return Array.isArray(rows) ? rows : null;
|
|
4080
|
+
}
|
|
4081
|
+
/**
|
|
4082
|
+
* Query one analytics metric. Large training-summary reads are serialized as small user/date
|
|
4083
|
+
* batches because that endpoint otherwise spends roughly a minute building one oversized report
|
|
4084
|
+
* before its gateway returns 504. Rejects plans above 100 total requests.
|
|
4085
|
+
*/
|
|
4086
|
+
async function queryAnalytics(client, args) {
|
|
4087
|
+
if (args.metric !== "training-summary-athlete" || args.userIds === void 0 || args.userIds.length === 0 || args.dateStart === void 0 || args.dateEnd === void 0) return requestAnalytics(client, args);
|
|
4088
|
+
const windows = splitDateRange(args.dateStart, args.dateEnd, TRAINING_SUMMARY_RANGE_DAYS);
|
|
4089
|
+
if (windows === null) return requestAnalytics(client, args);
|
|
4090
|
+
const uniqueUserIds = [...new Set(args.userIds)];
|
|
4091
|
+
if (Math.ceil(uniqueUserIds.length / TRAINING_SUMMARY_USER_BATCH) * windows.length > MAX_TRAINING_SUMMARY_REQUESTS) throw new RangeError(`Training summary is limited to ${MAX_TRAINING_SUMMARY_REQUESTS} batched requests; narrow the date range or pass fewer athletes.`);
|
|
4092
|
+
const requests = chunk(uniqueUserIds, TRAINING_SUMMARY_USER_BATCH).flatMap((userIds) => windows.map((window) => ({
|
|
4093
|
+
...args,
|
|
4094
|
+
userIds,
|
|
4095
|
+
dateStart: window.start,
|
|
4096
|
+
dateEnd: window.end
|
|
4097
|
+
})));
|
|
4098
|
+
if (requests.length === 1) return requestAnalytics(client, requests[0]);
|
|
4099
|
+
let merged = null;
|
|
4100
|
+
for (const request of requests) {
|
|
4101
|
+
const report = await requestAnalytics(client, request);
|
|
4102
|
+
const rows = reportRows(report);
|
|
4103
|
+
if (rows === null) throw new Error("Training summary returned an unexpected batched report shape.");
|
|
4104
|
+
if (merged === null) merged = {
|
|
4105
|
+
...report,
|
|
4106
|
+
rows: [...rows]
|
|
4107
|
+
};
|
|
4108
|
+
else merged.rows.push(...rows);
|
|
4109
|
+
}
|
|
4110
|
+
return merged;
|
|
4111
|
+
}
|
|
3962
4112
|
/**
|
|
3963
4113
|
* Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
|
|
3964
4114
|
* place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
|
|
@@ -3986,9 +4136,9 @@ function toNum(v) {
|
|
|
3986
4136
|
}
|
|
3987
4137
|
/**
|
|
3988
4138
|
* Team-wide training volume over an inclusive date window. The `training-summary-athlete`
|
|
3989
|
-
* analytics report
|
|
3990
|
-
*
|
|
3991
|
-
* volume/reps
|
|
4139
|
+
* analytics report returns one row per logged session across all `athleteIds`; `queryAnalytics`
|
|
4140
|
+
* splits oversized requests and merges those rows before this function groups them by athlete,
|
|
4141
|
+
* sums volume/reps, counts sessions, and rolls the athletes up into a team total. Athletes who
|
|
3992
4142
|
* logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
|
|
3993
4143
|
* all-time `fetchRosterActivity` snapshot, which has no date range.
|
|
3994
4144
|
*/
|
|
@@ -4112,6 +4262,7 @@ function classifyMainLift(title) {
|
|
|
4112
4262
|
return null;
|
|
4113
4263
|
}
|
|
4114
4264
|
const DEFAULT_MONTHS = 12;
|
|
4265
|
+
const WORKOUT_RANGE_DAYS = 180;
|
|
4115
4266
|
function pad2(n) {
|
|
4116
4267
|
return String(n).padStart(2, "0");
|
|
4117
4268
|
}
|
|
@@ -4129,12 +4280,18 @@ function isoDay(d) {
|
|
|
4129
4280
|
*/
|
|
4130
4281
|
async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
|
|
4131
4282
|
const months = opts.months ?? DEFAULT_MONTHS;
|
|
4283
|
+
if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
|
|
4132
4284
|
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
4133
|
-
const
|
|
4285
|
+
const startDay = isoDay(new Date(now.getFullYear(), now.getMonth() - (months - 1), 1));
|
|
4286
|
+
const endDay = isoDay(now);
|
|
4287
|
+
const windows = splitDateRange(startDay, endDay, WORKOUT_RANGE_DAYS) ?? [{
|
|
4288
|
+
start: startDay,
|
|
4289
|
+
end: endDay
|
|
4290
|
+
}];
|
|
4134
4291
|
const tally = /* @__PURE__ */ new Map();
|
|
4135
4292
|
let workouts = [];
|
|
4136
4293
|
try {
|
|
4137
|
-
|
|
4294
|
+
for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
|
|
4138
4295
|
} catch {
|
|
4139
4296
|
workouts = [];
|
|
4140
4297
|
}
|
|
@@ -4477,7 +4634,9 @@ var ExerciseLibrary = class {
|
|
|
4477
4634
|
};
|
|
4478
4635
|
}
|
|
4479
4636
|
async create(body) {
|
|
4480
|
-
|
|
4637
|
+
const requestBody = { ...body };
|
|
4638
|
+
if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
|
|
4639
|
+
return this.#writeThrough(CREATE_PATH, requestBody, "create");
|
|
4481
4640
|
}
|
|
4482
4641
|
async update(id, body) {
|
|
4483
4642
|
return this.#writeThrough(UPDATE_PATH(id), body, "update");
|
|
@@ -4485,7 +4644,7 @@ var ExerciseLibrary = class {
|
|
|
4485
4644
|
async #writeThrough(path, body, label) {
|
|
4486
4645
|
await this.ensureFresh();
|
|
4487
4646
|
const res = await this.#client.request("POST", path, { body });
|
|
4488
|
-
if (!res.ok) throw new Error(`Exercise ${label}
|
|
4647
|
+
if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
|
|
4489
4648
|
const ex = unwrapEnvelope(res.data);
|
|
4490
4649
|
if (ex && typeof ex === "object") {
|
|
4491
4650
|
checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
|
|
@@ -4844,7 +5003,7 @@ async function cmdExercise(client, rest) {
|
|
|
4844
5003
|
const { values, positionals } = parse(a, { file: { type: "string" } });
|
|
4845
5004
|
const id = toInt(need(positionals[0], "coach exercise update <id> <json>|--file f"), "id");
|
|
4846
5005
|
const body = await jsonInput(positionals[1], values.file);
|
|
4847
|
-
const exercise = validate(
|
|
5006
|
+
const exercise = validate(exerciseUpdateSchema, body, "exercise");
|
|
4848
5007
|
return out(await lib.update(id, exercise));
|
|
4849
5008
|
}
|
|
4850
5009
|
case "delete": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trainheroic-unofficial/cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -20,14 +20,14 @@
|
|
|
20
20
|
"skill"
|
|
21
21
|
],
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"zod": "^4.
|
|
24
|
-
"@trainheroic-unofficial/dto": "3.
|
|
25
|
-
"@trainheroic-unofficial/js": "3.
|
|
23
|
+
"zod": "^4.6.3",
|
|
24
|
+
"@trainheroic-unofficial/dto": "3.7.2",
|
|
25
|
+
"@trainheroic-unofficial/js": "3.7.2"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@types/node": "^26.
|
|
29
|
-
"tsdown": "^0.
|
|
30
|
-
"tsx": "^4.23.
|
|
28
|
+
"@types/node": "^26.5.1",
|
|
29
|
+
"tsdown": "^0.23.0",
|
|
30
|
+
"tsx": "^4.23.13",
|
|
31
31
|
"typescript": "^7.0.2",
|
|
32
32
|
"vitest": "^4.1.11"
|
|
33
33
|
},
|
|
@@ -123,6 +123,9 @@ $TH coach exercise delete 7721170 --yes # live DELETE /v5/exercises/{id} +
|
|
|
123
123
|
$TH coach exercise forget 7721170 --yes # cache-only, if you already deleted via the API
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
+
The create command supplies the provider-required `points_of_performance: ""` field when the
|
|
127
|
+
input omits it.
|
|
128
|
+
|
|
126
129
|
`$TH coach exercise stats` shows the cached row count.
|
|
127
130
|
|
|
128
131
|
## Building a workout
|
|
@@ -1064,6 +1064,9 @@ Full exercise library: `GET /v5/exerciseLibrary/all` (~2387 entries: 2067 exerci
|
|
|
1064
1064
|
`POST /2.0/coach/exercise/create`
|
|
1065
1065
|
|
|
1066
1066
|
Create exercises not in the standard library. You control the title and parameter types.
|
|
1067
|
+
TrainHeroic returns HTTP 500 when `points_of_performance` is absent, although an empty string is
|
|
1068
|
+
valid. The SDK exercise stores, MCP tool, and CLI supply `points_of_performance: ""` when callers
|
|
1069
|
+
omit it. Direct `TrainHeroicClient.request` calls must include the field explicitly.
|
|
1067
1070
|
|
|
1068
1071
|
**Request body:**
|
|
1069
1072
|
|