@trainheroic-unofficial/cli 3.5.2 → 3.7.1

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
- title: z.string().min(1),
446
- param_1_type: z.number().optional(),
447
- param_2_type: z.number().optional()
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,34 +810,258 @@ 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
- /**
789
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
790
- * metadata that is safe to send to telemetry: never the path, query string, request body,
791
- * response body, credentials, or session token.
792
- */
848
+ const MAX_REQUEST_KEYS = 50;
849
+ const MAX_RESPONSE_DEPTH = 4;
850
+ const MAX_RESPONSE_KEYS = 20;
851
+ const MAX_RESPONSE_ITEMS = 10;
852
+ const MAX_RESPONSE_NODES = 50;
853
+ const MAX_RESPONSE_STRING = 2e3;
854
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
855
+ "code",
856
+ "detail",
857
+ "details",
858
+ "error",
859
+ "error_code",
860
+ "errors",
861
+ "message",
862
+ "reason",
863
+ "status",
864
+ "status_code",
865
+ "success"
866
+ ]);
867
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
868
+ "data",
869
+ "received",
870
+ "response",
871
+ "result"
872
+ ]);
873
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
874
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
875
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
876
+ 0,
877
+ 1,
878
+ 2,
879
+ 3,
880
+ 4,
881
+ 5,
882
+ 6,
883
+ 7,
884
+ 10,
885
+ 11,
886
+ 12,
887
+ 13,
888
+ 14,
889
+ 18
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
+ }
896
+ function safeFieldName(key) {
897
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
898
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
899
+ return key;
900
+ }
901
+ function boundedEntries(object, limit) {
902
+ const entries = [];
903
+ for (const key of Object.keys(object)) {
904
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
905
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
906
+ if (entries.length >= limit) break;
907
+ }
908
+ return entries;
909
+ }
910
+ function safeRequestValue(key, value) {
911
+ if (key === "is_circuit" && typeof value === "boolean") return value;
912
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
913
+ }
914
+ function requestBodySummary(body) {
915
+ if (Array.isArray(body)) return {
916
+ type: "array",
917
+ length: body.length
918
+ };
919
+ if (body && typeof body === "object") {
920
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
921
+ const keys = entries.map(([key]) => safeFieldName(key));
922
+ const values = {};
923
+ const arrayLengths = {};
924
+ for (const [key, value] of entries) {
925
+ const safeValue = safeRequestValue(key, value);
926
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
927
+ if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
928
+ }
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 {
934
+ type: "object",
935
+ keys,
936
+ ...Object.keys(values).length > 0 ? { values } : {},
937
+ ...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
938
+ ...span === null ? {} : { dateSpanDays: span }
939
+ };
940
+ }
941
+ const primitive = typeof body;
942
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
943
+ }
944
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
945
+ if (budget.nodes <= 0) return "[Truncated]";
946
+ budget.nodes -= 1;
947
+ if (value === null) return null;
948
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
949
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
950
+ if (typeof value === "string") return redactText(value);
951
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
952
+ if (Array.isArray(value)) {
953
+ const result = [];
954
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
955
+ if (budget.nodes <= 0) {
956
+ result.push("[Truncated]");
957
+ break;
958
+ }
959
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
960
+ }
961
+ return result;
962
+ }
963
+ if (value && typeof value === "object") {
964
+ const result = {};
965
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
966
+ if (budget.nodes <= 0) {
967
+ result.truncated = "[Truncated]";
968
+ break;
969
+ }
970
+ const safeKey = safeFieldName(key);
971
+ const safeValue = safeRequestValue(key, item);
972
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
973
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
974
+ else if (safeValue !== void 0) {
975
+ budget.nodes -= 1;
976
+ result[safeKey] = safeValue;
977
+ }
978
+ }
979
+ return result;
980
+ }
981
+ return `[${typeof value}]`;
982
+ }
983
+ function responseBodyDiagnostics(body, budget, depth = 0) {
984
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
985
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
986
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
987
+ const object = body;
988
+ const result = {};
989
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
990
+ if (activeBudget.nodes <= 0) {
991
+ result.truncated = "[Truncated]";
992
+ break;
993
+ }
994
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
995
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
996
+ continue;
997
+ }
998
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
999
+ activeBudget.nodes -= 1;
1000
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
1001
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
1002
+ }
1003
+ }
1004
+ if (Object.keys(result).length > 0) return result;
1005
+ return { type: "object" };
1006
+ }
1007
+ function parseResponseText(text) {
1008
+ if (text.length === 0) return text;
1009
+ try {
1010
+ return JSON.parse(text);
1011
+ } catch {
1012
+ return text;
1013
+ }
1014
+ }
1015
+ function safeRequestBodySummary(body) {
1016
+ try {
1017
+ return requestBodySummary(body);
1018
+ } catch {
1019
+ return { type: "other" };
1020
+ }
1021
+ }
1022
+ function safeResponseBodyDiagnostics(body) {
1023
+ try {
1024
+ return responseBodyDiagnostics(body);
1025
+ } catch {
1026
+ return "[Unavailable]";
1027
+ }
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
+ }
1035
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
793
1036
  var TrainHeroicHttpError = class extends Error {
794
1037
  name = "TrainHeroicHttpError";
795
1038
  method;
796
1039
  status;
797
1040
  host;
798
- constructor(method, url, status) {
1041
+ requestBody;
1042
+ responseBody;
1043
+ constructor(method, url, status, diagnostics = {}) {
799
1044
  const parsed = new URL(url);
800
1045
  const normalizedMethod = method.toUpperCase();
801
1046
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
802
1047
  this.method = normalizedMethod;
803
1048
  this.status = status;
804
1049
  this.host = parsed.host;
1050
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
1051
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
805
1052
  }
806
1053
  };
807
1054
  /** Call observability hooks without allowing them to change SDK behavior. */
808
- function notifyHttpError(handler, method, url, status) {
1055
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
809
1056
  if (!handler) return;
810
1057
  try {
811
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
1058
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
812
1059
  } catch {}
813
1060
  }
814
1061
  //#endregion
1062
+ //#region ../js/src/transport.ts
1063
+ const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
1064
+ //#endregion
815
1065
  //#region ../js/src/auth.ts
816
1066
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
817
1067
  /**
@@ -835,7 +1085,7 @@ function authUrl() {
835
1085
  */
836
1086
  async function loginTrainHeroic(email, password, options = {}) {
837
1087
  const url = authUrl();
838
- const res = await fetch(url, {
1088
+ const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
839
1089
  method: "POST",
840
1090
  headers: {
841
1091
  "content-type": "application/x-www-form-urlencoded",
@@ -847,6 +1097,7 @@ async function loginTrainHeroic(email, password, options = {}) {
847
1097
  }).toString()
848
1098
  });
849
1099
  if (!res.ok) {
1100
+ await res.body?.cancel().catch(() => {});
850
1101
  notifyHttpError(options.onHttpError, "POST", url, res.status);
851
1102
  return null;
852
1103
  }
@@ -860,122 +1111,40 @@ async function loginTrainHeroic(email, password, options = {}) {
860
1111
  };
861
1112
  }
862
1113
  //#endregion
863
- //#region ../js/src/client.ts
864
- const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
865
- const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
866
- /**
867
- * Resolve an API host, allowing an env override. The override exists so a test harness can point
868
- * the client at a local fake backend (and it doubles as a staging knob); production leaves these
869
- * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
870
- * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
871
- * read per request (not at module load) so a value the harness sets in the child env always wins.
872
- */
873
- function envBase(key, fallback) {
874
- const v = (globalThis.process?.env)?.[key];
875
- return v && v.length > 0 ? v : fallback;
876
- }
877
- var TrainHeroicAuthError = class extends Error {
878
- name = "TrainHeroicAuthError";
879
- };
1114
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/chunk.mjs
880
1115
  /**
881
- * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
882
- * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
883
- * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
884
- * TrainHeroic has no refresh token and sessions expire after ~1-2h.
1116
+ * Splits an array into smaller arrays of a specified length.
885
1117
  *
886
- * Anything that wants a session to outlive one client owns that itself: pass a previously
887
- * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
888
- * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
889
- * invocation is a fresh process — because otherwise every operation replays the password.
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']]
890
1137
  */
891
- var TrainHeroicClient = class {
892
- #email;
893
- #password;
894
- #onSession;
895
- #onHttpError;
896
- #sessionId;
897
- #loginInFlight = null;
898
- constructor(email, password, sessionId = null, options = {}) {
899
- this.#email = email;
900
- this.#password = password;
901
- this.#sessionId = sessionId;
902
- this.#onSession = options.onSession;
903
- this.#onHttpError = options.onHttpError;
904
- }
905
- get sessionId() {
906
- return this.#sessionId;
907
- }
908
- async #ensureSession() {
909
- if (this.#sessionId) return this.#sessionId;
910
- this.#loginInFlight ??= this.#login();
911
- try {
912
- return await this.#loginInFlight;
913
- } finally {
914
- this.#loginInFlight = null;
915
- }
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);
916
1146
  }
917
- async #login() {
918
- const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
919
- if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
920
- this.#sessionId = session.sessionId;
921
- try {
922
- this.#onSession?.(this.#sessionId);
923
- } catch {}
924
- return this.#sessionId;
925
- }
926
- async request(method, path, options = {}) {
927
- const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
928
- let session = await this.#ensureSession();
929
- let res = await this.#send(method, url, session, options.body);
930
- if (res.status === 401 || res.status === 403) {
931
- if (this.#sessionId === session) this.#sessionId = null;
932
- session = await this.#ensureSession();
933
- res = await this.#send(method, url, session, options.body);
934
- }
935
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
936
- const text = await res.text();
937
- let data = text;
938
- if (text.length > 0) try {
939
- data = JSON.parse(text);
940
- } catch {
941
- data = text;
942
- }
943
- return {
944
- status: res.status,
945
- ok: res.ok,
946
- data
947
- };
948
- }
949
- #send(method, url, session, body) {
950
- const upper = method.toUpperCase();
951
- const headers = {
952
- accept: "application/json",
953
- "session-token": session
954
- };
955
- const init = {
956
- method: upper,
957
- headers
958
- };
959
- if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
960
- headers["content-type"] = "application/json";
961
- init.body = JSON.stringify(body);
962
- }
963
- return fetch(url, init);
964
- }
965
- };
966
- //#endregion
967
- //#region ../js/src/response-check.ts
968
- /**
969
- * Validate an API response against its (loose) expected shape and warn once on drift.
970
- * Never throws: callers keep working via defensive coercion. This only surfaces a signal
971
- * when TrainHeroic renames or drops a field we read.
972
- */
973
- function checkResponse(schema, data, label) {
974
- const result = schema.safeParse(data);
975
- if (result.success) return;
976
- const issue = result.error.issues[0];
977
- const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
978
- console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1147
+ return result;
979
1148
  }
980
1149
  //#endregion
981
1150
  //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
@@ -1242,6 +1411,141 @@ function assertPositiveInteger(value, label) {
1242
1411
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1243
1412
  }
1244
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
1245
1549
  //#region ../js/src/athlete.ts
1246
1550
  async function getJson(client, path, label) {
1247
1551
  const res = await client.request("GET", path);
@@ -1369,27 +1673,9 @@ async function programWorkoutOnDate(client, date, programWorkoutId) {
1369
1673
  if (target === void 0) throw new Error(`No workout with id ${programWorkoutId} on ${date}. Get the id and date from athlete_workouts.`);
1370
1674
  return target;
1371
1675
  }
1372
- /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
1373
- function shiftDate(iso, days) {
1374
- const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
1375
- d.setUTCDate(d.getUTCDate() + days);
1376
- return d.toISOString().slice(0, 10);
1377
- }
1378
- /** 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. */
1379
1677
  function dateWindows(startDate, endDate, windowDays) {
1380
- const size = Math.max(1, Math.floor(windowDays));
1381
- const windows = [];
1382
- let cursor = startDate;
1383
- while (cursor <= endDate) {
1384
- const winEnd = shiftDate(cursor, size - 1);
1385
- const clamped = winEnd > endDate ? endDate : winEnd;
1386
- windows.push({
1387
- start: cursor,
1388
- end: clamped
1389
- });
1390
- cursor = shiftDate(clamped, 1);
1391
- }
1392
- return windows;
1678
+ return splitDateRange(startDate, endDate, Math.max(1, Math.floor(windowDays))) ?? [];
1393
1679
  }
1394
1680
  /**
1395
1681
  * Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
@@ -3751,12 +4037,15 @@ const ANALYTICS_BODY_KEY = {
3751
4037
  exerciseId: "exercise_id",
3752
4038
  useMetric: "use_metric"
3753
4039
  };
4040
+ const TRAINING_SUMMARY_USER_BATCH = 5;
4041
+ const TRAINING_SUMMARY_RANGE_DAYS = 90;
4042
+ const MAX_TRAINING_SUMMARY_REQUESTS = 100;
3754
4043
  /**
3755
4044
  * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
3756
4045
  * athlete metrics need one or more `userIds` (passed together — the report returns a row per
3757
4046
  * athlete). Throws a readable Error when a required input is missing or the call fails.
3758
4047
  */
3759
- async function queryAnalytics(client, args) {
4048
+ async function requestAnalytics(client, args) {
3760
4049
  const spec = ANALYTICS_METRICS[args.metric];
3761
4050
  const body = {};
3762
4051
  if (spec.scope === "team") {
@@ -3784,6 +4073,42 @@ async function queryAnalytics(client, args) {
3784
4073
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3785
4074
  return res.data;
3786
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
+ }
3787
4112
  /**
3788
4113
  * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
3789
4114
  * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
@@ -3811,9 +4136,9 @@ function toNum(v) {
3811
4136
  }
3812
4137
  /**
3813
4138
  * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
3814
- * analytics report already returns the team in one call — one row per logged session across all
3815
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
3816
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
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
3817
4142
  * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
3818
4143
  * all-time `fetchRosterActivity` snapshot, which has no date range.
3819
4144
  */
@@ -3937,6 +4262,7 @@ function classifyMainLift(title) {
3937
4262
  return null;
3938
4263
  }
3939
4264
  const DEFAULT_MONTHS = 12;
4265
+ const WORKOUT_RANGE_DAYS = 180;
3940
4266
  function pad2(n) {
3941
4267
  return String(n).padStart(2, "0");
3942
4268
  }
@@ -3954,12 +4280,18 @@ function isoDay(d) {
3954
4280
  */
3955
4281
  async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3956
4282
  const months = opts.months ?? DEFAULT_MONTHS;
4283
+ if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
3957
4284
  const now = opts.now ?? /* @__PURE__ */ new Date();
3958
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
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
+ }];
3959
4291
  const tally = /* @__PURE__ */ new Map();
3960
4292
  let workouts = [];
3961
4293
  try {
3962
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
4294
+ for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
3963
4295
  } catch {
3964
4296
  workouts = [];
3965
4297
  }
@@ -4302,7 +4634,9 @@ var ExerciseLibrary = class {
4302
4634
  };
4303
4635
  }
4304
4636
  async create(body) {
4305
- return this.#writeThrough(CREATE_PATH, body, "create");
4637
+ const requestBody = { ...body };
4638
+ if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
4639
+ return this.#writeThrough(CREATE_PATH, requestBody, "create");
4306
4640
  }
4307
4641
  async update(id, body) {
4308
4642
  return this.#writeThrough(UPDATE_PATH(id), body, "update");
@@ -4310,7 +4644,7 @@ var ExerciseLibrary = class {
4310
4644
  async #writeThrough(path, body, label) {
4311
4645
  await this.ensureFresh();
4312
4646
  const res = await this.#client.request("POST", path, { body });
4313
- if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
4647
+ if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
4314
4648
  const ex = unwrapEnvelope(res.data);
4315
4649
  if (ex && typeof ex === "object") {
4316
4650
  checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
@@ -4669,7 +5003,7 @@ async function cmdExercise(client, rest) {
4669
5003
  const { values, positionals } = parse(a, { file: { type: "string" } });
4670
5004
  const id = toInt(need(positionals[0], "coach exercise update <id> <json>|--file f"), "id");
4671
5005
  const body = await jsonInput(positionals[1], values.file);
4672
- const exercise = validate(exerciseCreateSchema, body, "exercise");
5006
+ const exercise = validate(exerciseUpdateSchema, body, "exercise");
4673
5007
  return out(await lib.update(id, exercise));
4674
5008
  }
4675
5009
  case "delete": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "3.5.2",
3
+ "version": "3.7.1",
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.4.3",
24
- "@trainheroic-unofficial/dto": "3.5.2",
25
- "@trainheroic-unofficial/js": "3.5.2"
23
+ "zod": "^4.6.3",
24
+ "@trainheroic-unofficial/dto": "3.7.1",
25
+ "@trainheroic-unofficial/js": "3.7.1"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.3.0",
29
- "tsdown": "^0.22.14",
30
- "tsx": "^4.23.12",
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