@trainheroic-unofficial/js 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/index.mjs CHANGED
@@ -2,34 +2,258 @@ import { blockSpecSchema, exerciseLibraryResponseSchema, exerciseResponseSchema,
2
2
  import { chunk, uniq } from "es-toolkit/array";
3
3
  import { z } from "zod";
4
4
  export * from "@trainheroic-unofficial/dto";
5
+ //#region src/date-window.ts
6
+ const DAY_MS = 864e5;
7
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/u;
8
+ const MAX_DATE_WINDOWS = 100;
9
+ function dayNumber(value) {
10
+ if (!ISO_DAY.test(value)) return null;
11
+ const timestamp = Date.parse(`${value}T00:00:00Z`);
12
+ if (!Number.isFinite(timestamp) || new Date(timestamp).toISOString().slice(0, 10) !== value) return null;
13
+ return timestamp / DAY_MS;
14
+ }
15
+ function isoDay$1(day) {
16
+ return (/* @__PURE__ */ new Date(day * DAY_MS)).toISOString().slice(0, 10);
17
+ }
18
+ /** Number of calendar days in an inclusive ISO-date range, or null for an invalid range. */
19
+ function dateSpanDays(start, end) {
20
+ const first = dayNumber(start);
21
+ const last = dayNumber(end);
22
+ return first === null || last === null || first > last ? null : last - first + 1;
23
+ }
24
+ /** Split an inclusive ISO-date range into at most 100 ordered, non-overlapping windows. */
25
+ function splitDateRange(start, end, maxDays) {
26
+ const first = dayNumber(start);
27
+ const last = dayNumber(end);
28
+ if (first === null || last === null || first > last) return null;
29
+ if (!Number.isSafeInteger(maxDays) || maxDays < 1) throw new RangeError("maxDays must be a positive integer.");
30
+ 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.`);
31
+ const windows = [];
32
+ for (let cursor = first; cursor <= last; cursor += maxDays) windows.push({
33
+ start: isoDay$1(cursor),
34
+ end: isoDay$1(Math.min(cursor + maxDays - 1, last))
35
+ });
36
+ return windows;
37
+ }
38
+ //#endregion
5
39
  //#region src/http-error.ts
6
- /**
7
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
8
- * metadata that is safe to send to telemetry: never the path, query string, request body,
9
- * response body, credentials, or session token.
10
- */
40
+ const MAX_REQUEST_KEYS = 50;
41
+ const MAX_RESPONSE_DEPTH = 4;
42
+ const MAX_RESPONSE_KEYS = 20;
43
+ const MAX_RESPONSE_ITEMS = 10;
44
+ const MAX_RESPONSE_NODES = 50;
45
+ const MAX_RESPONSE_STRING = 2e3;
46
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
47
+ "code",
48
+ "detail",
49
+ "details",
50
+ "error",
51
+ "error_code",
52
+ "errors",
53
+ "message",
54
+ "reason",
55
+ "status",
56
+ "status_code",
57
+ "success"
58
+ ]);
59
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
60
+ "data",
61
+ "received",
62
+ "response",
63
+ "result"
64
+ ]);
65
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
66
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
67
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
68
+ 0,
69
+ 1,
70
+ 2,
71
+ 3,
72
+ 4,
73
+ 5,
74
+ 6,
75
+ 7,
76
+ 10,
77
+ 11,
78
+ 12,
79
+ 13,
80
+ 14,
81
+ 18
82
+ ]);
83
+ /** Keep provider diagnostics useful while removing common credentials and direct identifiers. */
84
+ function redactText(value) {
85
+ 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]");
86
+ return value.length <= MAX_RESPONSE_STRING ? redacted : `${redacted}…[truncated]`;
87
+ }
88
+ function safeFieldName(key) {
89
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
90
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
91
+ return key;
92
+ }
93
+ function boundedEntries(object, limit) {
94
+ const entries = [];
95
+ for (const key of Object.keys(object)) {
96
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
97
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
98
+ if (entries.length >= limit) break;
99
+ }
100
+ return entries;
101
+ }
102
+ function safeRequestValue(key, value) {
103
+ if (key === "is_circuit" && typeof value === "boolean") return value;
104
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
105
+ }
106
+ function requestBodySummary(body) {
107
+ if (Array.isArray(body)) return {
108
+ type: "array",
109
+ length: body.length
110
+ };
111
+ if (body && typeof body === "object") {
112
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
113
+ const keys = entries.map(([key]) => safeFieldName(key));
114
+ const values = {};
115
+ const arrayLengths = {};
116
+ for (const [key, value] of entries) {
117
+ const safeValue = safeRequestValue(key, value);
118
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
119
+ if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
120
+ }
121
+ const byKey = new Map(entries);
122
+ const dateStart = byKey.get("date_start");
123
+ const dateEnd = byKey.get("date_end");
124
+ const span = typeof dateStart === "string" && typeof dateEnd === "string" ? dateSpanDays(dateStart, dateEnd) : null;
125
+ return {
126
+ type: "object",
127
+ keys,
128
+ ...Object.keys(values).length > 0 ? { values } : {},
129
+ ...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
130
+ ...span === null ? {} : { dateSpanDays: span }
131
+ };
132
+ }
133
+ const primitive = typeof body;
134
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
135
+ }
136
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
137
+ if (budget.nodes <= 0) return "[Truncated]";
138
+ budget.nodes -= 1;
139
+ if (value === null) return null;
140
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
141
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
142
+ if (typeof value === "string") return redactText(value);
143
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
144
+ if (Array.isArray(value)) {
145
+ const result = [];
146
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
147
+ if (budget.nodes <= 0) {
148
+ result.push("[Truncated]");
149
+ break;
150
+ }
151
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
152
+ }
153
+ return result;
154
+ }
155
+ if (value && typeof value === "object") {
156
+ const result = {};
157
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
158
+ if (budget.nodes <= 0) {
159
+ result.truncated = "[Truncated]";
160
+ break;
161
+ }
162
+ const safeKey = safeFieldName(key);
163
+ const safeValue = safeRequestValue(key, item);
164
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
165
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
166
+ else if (safeValue !== void 0) {
167
+ budget.nodes -= 1;
168
+ result[safeKey] = safeValue;
169
+ }
170
+ }
171
+ return result;
172
+ }
173
+ return `[${typeof value}]`;
174
+ }
175
+ function responseBodyDiagnostics(body, budget, depth = 0) {
176
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
177
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
178
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
179
+ const object = body;
180
+ const result = {};
181
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
182
+ if (activeBudget.nodes <= 0) {
183
+ result.truncated = "[Truncated]";
184
+ break;
185
+ }
186
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
187
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
188
+ continue;
189
+ }
190
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
191
+ activeBudget.nodes -= 1;
192
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
193
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
194
+ }
195
+ }
196
+ if (Object.keys(result).length > 0) return result;
197
+ return { type: "object" };
198
+ }
199
+ function parseResponseText(text) {
200
+ if (text.length === 0) return text;
201
+ try {
202
+ return JSON.parse(text);
203
+ } catch {
204
+ return text;
205
+ }
206
+ }
207
+ function safeRequestBodySummary(body) {
208
+ try {
209
+ return requestBodySummary(body);
210
+ } catch {
211
+ return { type: "other" };
212
+ }
213
+ }
214
+ function safeResponseBodyDiagnostics(body) {
215
+ try {
216
+ return responseBodyDiagnostics(body);
217
+ } catch {
218
+ return "[Unavailable]";
219
+ }
220
+ }
221
+ /** Format a bounded provider diagnostic for an in-band tool or SDK error. */
222
+ function trainHeroicApiErrorMessage(label, status, responseBody) {
223
+ const diagnostic = safeResponseBodyDiagnostics(responseBody);
224
+ 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);
225
+ return detail && detail !== "{\"type\":\"object\"}" ? `${label} failed (HTTP ${status}): ${detail}` : `${label} failed (HTTP ${status}).`;
226
+ }
227
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
11
228
  var TrainHeroicHttpError = class extends Error {
12
229
  name = "TrainHeroicHttpError";
13
230
  method;
14
231
  status;
15
232
  host;
16
- constructor(method, url, status) {
233
+ requestBody;
234
+ responseBody;
235
+ constructor(method, url, status, diagnostics = {}) {
17
236
  const parsed = new URL(url);
18
237
  const normalizedMethod = method.toUpperCase();
19
238
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
20
239
  this.method = normalizedMethod;
21
240
  this.status = status;
22
241
  this.host = parsed.host;
242
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
243
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
23
244
  }
24
245
  };
25
246
  /** Call observability hooks without allowing them to change SDK behavior. */
26
- function notifyHttpError(handler, method, url, status) {
247
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
27
248
  if (!handler) return;
28
249
  try {
29
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
250
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
30
251
  } catch {}
31
252
  }
32
253
  //#endregion
254
+ //#region src/transport.ts
255
+ const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
256
+ //#endregion
33
257
  //#region src/auth.ts
34
258
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
35
259
  /**
@@ -53,7 +277,7 @@ function authUrl() {
53
277
  */
54
278
  async function loginTrainHeroic(email, password, options = {}) {
55
279
  const url = authUrl();
56
- const res = await fetch(url, {
280
+ const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
57
281
  method: "POST",
58
282
  headers: {
59
283
  "content-type": "application/x-www-form-urlencoded",
@@ -65,6 +289,7 @@ async function loginTrainHeroic(email, password, options = {}) {
65
289
  }).toString()
66
290
  });
67
291
  if (!res.ok) {
292
+ await res.body?.cancel().catch(() => {});
68
293
  notifyHttpError(options.onHttpError, "POST", url, res.status);
69
294
  return null;
70
295
  }
@@ -78,124 +303,6 @@ async function loginTrainHeroic(email, password, options = {}) {
78
303
  };
79
304
  }
80
305
  //#endregion
81
- //#region src/client.ts
82
- const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
83
- const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
84
- /**
85
- * Resolve an API host, allowing an env override. The override exists so a test harness can point
86
- * the client at a local fake backend (and it doubles as a staging knob); production leaves these
87
- * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
88
- * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
89
- * read per request (not at module load) so a value the harness sets in the child env always wins.
90
- */
91
- function envBase(key, fallback) {
92
- const v = (globalThis.process?.env)?.[key];
93
- return v && v.length > 0 ? v : fallback;
94
- }
95
- var TrainHeroicAuthError = class extends Error {
96
- name = "TrainHeroicAuthError";
97
- };
98
- /**
99
- * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
100
- * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
101
- * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
102
- * TrainHeroic has no refresh token and sessions expire after ~1-2h.
103
- *
104
- * Anything that wants a session to outlive one client owns that itself: pass a previously
105
- * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
106
- * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
107
- * invocation is a fresh process — because otherwise every operation replays the password.
108
- */
109
- var TrainHeroicClient = class {
110
- #email;
111
- #password;
112
- #onSession;
113
- #onHttpError;
114
- #sessionId;
115
- #loginInFlight = null;
116
- constructor(email, password, sessionId = null, options = {}) {
117
- this.#email = email;
118
- this.#password = password;
119
- this.#sessionId = sessionId;
120
- this.#onSession = options.onSession;
121
- this.#onHttpError = options.onHttpError;
122
- }
123
- get sessionId() {
124
- return this.#sessionId;
125
- }
126
- async #ensureSession() {
127
- if (this.#sessionId) return this.#sessionId;
128
- this.#loginInFlight ??= this.#login();
129
- try {
130
- return await this.#loginInFlight;
131
- } finally {
132
- this.#loginInFlight = null;
133
- }
134
- }
135
- async #login() {
136
- const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
137
- if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
138
- this.#sessionId = session.sessionId;
139
- try {
140
- this.#onSession?.(this.#sessionId);
141
- } catch {}
142
- return this.#sessionId;
143
- }
144
- async request(method, path, options = {}) {
145
- const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
146
- let session = await this.#ensureSession();
147
- let res = await this.#send(method, url, session, options.body);
148
- if (res.status === 401 || res.status === 403) {
149
- if (this.#sessionId === session) this.#sessionId = null;
150
- session = await this.#ensureSession();
151
- res = await this.#send(method, url, session, options.body);
152
- }
153
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
154
- const text = await res.text();
155
- let data = text;
156
- if (text.length > 0) try {
157
- data = JSON.parse(text);
158
- } catch {
159
- data = text;
160
- }
161
- return {
162
- status: res.status,
163
- ok: res.ok,
164
- data
165
- };
166
- }
167
- #send(method, url, session, body) {
168
- const upper = method.toUpperCase();
169
- const headers = {
170
- accept: "application/json",
171
- "session-token": session
172
- };
173
- const init = {
174
- method: upper,
175
- headers
176
- };
177
- if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
178
- headers["content-type"] = "application/json";
179
- init.body = JSON.stringify(body);
180
- }
181
- return fetch(url, init);
182
- }
183
- };
184
- //#endregion
185
- //#region src/response-check.ts
186
- /**
187
- * Validate an API response against its (loose) expected shape and warn once on drift.
188
- * Never throws: callers keep working via defensive coercion. This only surfaces a signal
189
- * when TrainHeroic renames or drops a field we read.
190
- */
191
- function checkResponse(schema, data, label) {
192
- const result = schema.safeParse(data);
193
- if (result.success) return;
194
- const issue = result.error.issues[0];
195
- const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
196
- console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
197
- }
198
- //#endregion
199
306
  //#region src/exercise-util.ts
200
307
  /**
201
308
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -448,6 +555,141 @@ function assertPositiveInteger(value, label) {
448
555
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
449
556
  }
450
557
  //#endregion
558
+ //#region src/client.ts
559
+ const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
560
+ const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
561
+ const MAX_REQUEST_CONCURRENCY = 4;
562
+ /**
563
+ * Resolve an API host, allowing an env override. The override exists so a test harness can point
564
+ * the client at a local fake backend (and it doubles as a staging knob); production leaves these
565
+ * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
566
+ * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
567
+ * read per request (not at module load) so a value the harness sets in the child env always wins.
568
+ */
569
+ function envBase(key, fallback) {
570
+ const v = (globalThis.process?.env)?.[key];
571
+ return v && v.length > 0 ? v : fallback;
572
+ }
573
+ var TrainHeroicAuthError = class extends Error {
574
+ name = "TrainHeroicAuthError";
575
+ };
576
+ /**
577
+ * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
578
+ * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
579
+ * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
580
+ * TrainHeroic has no refresh token and sessions expire after ~1-2h.
581
+ *
582
+ * Anything that wants a session to outlive one client owns that itself: pass a previously
583
+ * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
584
+ * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
585
+ * invocation is a fresh process — because otherwise every operation replays the password.
586
+ */
587
+ var TrainHeroicClient = class {
588
+ #email;
589
+ #password;
590
+ #onSession;
591
+ #onHttpError;
592
+ #transport;
593
+ #requestLimit = createLimiter(MAX_REQUEST_CONCURRENCY);
594
+ #sessionId;
595
+ #loginInFlight = null;
596
+ constructor(email, password, sessionId = null, options = {}) {
597
+ this.#email = email;
598
+ this.#password = password;
599
+ this.#sessionId = sessionId;
600
+ this.#onSession = options.onSession;
601
+ this.#onHttpError = options.onHttpError;
602
+ this.#transport = options.transport ?? defaultTrainHeroicTransport;
603
+ }
604
+ get sessionId() {
605
+ return this.#sessionId;
606
+ }
607
+ async #ensureSession() {
608
+ if (this.#sessionId) return this.#sessionId;
609
+ this.#loginInFlight ??= this.#login();
610
+ try {
611
+ return await this.#loginInFlight;
612
+ } finally {
613
+ this.#loginInFlight = null;
614
+ }
615
+ }
616
+ async #login() {
617
+ const session = await loginTrainHeroic(this.#email, this.#password, {
618
+ ...this.#onHttpError ? { onHttpError: this.#onHttpError } : {},
619
+ transport: this.#transport
620
+ });
621
+ if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
622
+ this.#sessionId = session.sessionId;
623
+ try {
624
+ this.#onSession?.(this.#sessionId);
625
+ } catch {}
626
+ return this.#sessionId;
627
+ }
628
+ async request(method, path, options = {}) {
629
+ await this.#ensureSession();
630
+ return this.#requestLimit.run(() => this.#request(method, path, options));
631
+ }
632
+ async #request(method, path, options) {
633
+ const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
634
+ let session = await this.#ensureSession();
635
+ let res = await this.#send(method, url, session, options.body);
636
+ if (res.status === 401 || res.status === 403) {
637
+ await res.body?.cancel().catch(() => {});
638
+ if (this.#sessionId === session) this.#sessionId = null;
639
+ session = await this.#ensureSession();
640
+ res = await this.#send(method, url, session, options.body);
641
+ }
642
+ const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
643
+ let text;
644
+ try {
645
+ text = await res.text();
646
+ } catch (error) {
647
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
648
+ throw error;
649
+ }
650
+ const data = parseResponseText(text);
651
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
652
+ requestBody: options.body,
653
+ responseBody: data
654
+ });
655
+ return {
656
+ status: res.status,
657
+ ok: res.ok,
658
+ data
659
+ };
660
+ }
661
+ #send(method, url, session, body) {
662
+ const upper = method.toUpperCase();
663
+ const headers = {
664
+ accept: "application/json",
665
+ "session-token": session
666
+ };
667
+ const init = {
668
+ method: upper,
669
+ headers
670
+ };
671
+ if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
672
+ headers["content-type"] = "application/json";
673
+ init.body = JSON.stringify(body);
674
+ }
675
+ return this.#transport(url, init);
676
+ }
677
+ };
678
+ //#endregion
679
+ //#region src/response-check.ts
680
+ /**
681
+ * Validate an API response against its (loose) expected shape and warn once on drift.
682
+ * Never throws: callers keep working via defensive coercion. This only surfaces a signal
683
+ * when TrainHeroic renames or drops a field we read.
684
+ */
685
+ function checkResponse(schema, data, label) {
686
+ const result = schema.safeParse(data);
687
+ if (result.success) return;
688
+ const issue = result.error.issues[0];
689
+ const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
690
+ console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
691
+ }
692
+ //#endregion
451
693
  //#region src/athlete.ts
452
694
  async function getJson(client, path, label) {
453
695
  const res = await client.request("GET", path);
@@ -575,27 +817,9 @@ async function programWorkoutOnDate(client, date, programWorkoutId) {
575
817
  if (target === void 0) throw new Error(`No workout with id ${programWorkoutId} on ${date}. Get the id and date from athlete_workouts.`);
576
818
  return target;
577
819
  }
578
- /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
579
- function shiftDate(iso, days) {
580
- const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
581
- d.setUTCDate(d.getUTCDate() + days);
582
- return d.toISOString().slice(0, 10);
583
- }
584
- /** Split an inclusive `[start, end]` range into consecutive non-overlapping windows of `windowDays`. */
820
+ /** Split an inclusive range into at most 100 consecutive, non-overlapping windows. */
585
821
  function dateWindows(startDate, endDate, windowDays) {
586
- const size = Math.max(1, Math.floor(windowDays));
587
- const windows = [];
588
- let cursor = startDate;
589
- while (cursor <= endDate) {
590
- const winEnd = shiftDate(cursor, size - 1);
591
- const clamped = winEnd > endDate ? endDate : winEnd;
592
- windows.push({
593
- start: cursor,
594
- end: clamped
595
- });
596
- cursor = shiftDate(clamped, 1);
597
- }
598
- return windows;
822
+ return splitDateRange(startDate, endDate, Math.max(1, Math.floor(windowDays))) ?? [];
599
823
  }
600
824
  /**
601
825
  * Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
@@ -2963,12 +3187,15 @@ const ANALYTICS_BODY_KEY = {
2963
3187
  exerciseId: "exercise_id",
2964
3188
  useMetric: "use_metric"
2965
3189
  };
3190
+ const TRAINING_SUMMARY_USER_BATCH = 5;
3191
+ const TRAINING_SUMMARY_RANGE_DAYS = 90;
3192
+ const MAX_TRAINING_SUMMARY_REQUESTS = 100;
2966
3193
  /**
2967
3194
  * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2968
3195
  * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2969
3196
  * athlete). Throws a readable Error when a required input is missing or the call fails.
2970
3197
  */
2971
- async function queryAnalytics(client, args) {
3198
+ async function requestAnalytics(client, args) {
2972
3199
  const spec = ANALYTICS_METRICS[args.metric];
2973
3200
  const body = {};
2974
3201
  if (spec.scope === "team") {
@@ -2996,6 +3223,42 @@ async function queryAnalytics(client, args) {
2996
3223
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2997
3224
  return res.data;
2998
3225
  }
3226
+ function reportRows(report) {
3227
+ if (report === null || typeof report !== "object") return null;
3228
+ const rows = report.rows;
3229
+ return Array.isArray(rows) ? rows : null;
3230
+ }
3231
+ /**
3232
+ * Query one analytics metric. Large training-summary reads are serialized as small user/date
3233
+ * batches because that endpoint otherwise spends roughly a minute building one oversized report
3234
+ * before its gateway returns 504. Rejects plans above 100 total requests.
3235
+ */
3236
+ async function queryAnalytics(client, args) {
3237
+ 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);
3238
+ const windows = splitDateRange(args.dateStart, args.dateEnd, TRAINING_SUMMARY_RANGE_DAYS);
3239
+ if (windows === null) return requestAnalytics(client, args);
3240
+ const uniqueUserIds = [...new Set(args.userIds)];
3241
+ 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.`);
3242
+ const requests = chunk(uniqueUserIds, TRAINING_SUMMARY_USER_BATCH).flatMap((userIds) => windows.map((window) => ({
3243
+ ...args,
3244
+ userIds,
3245
+ dateStart: window.start,
3246
+ dateEnd: window.end
3247
+ })));
3248
+ if (requests.length === 1) return requestAnalytics(client, requests[0]);
3249
+ let merged = null;
3250
+ for (const request of requests) {
3251
+ const report = await requestAnalytics(client, request);
3252
+ const rows = reportRows(report);
3253
+ if (rows === null) throw new Error("Training summary returned an unexpected batched report shape.");
3254
+ if (merged === null) merged = {
3255
+ ...report,
3256
+ rows: [...rows]
3257
+ };
3258
+ else merged.rows.push(...rows);
3259
+ }
3260
+ return merged;
3261
+ }
2999
3262
  /**
3000
3263
  * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
3001
3264
  * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
@@ -3023,9 +3286,9 @@ function toNum(v) {
3023
3286
  }
3024
3287
  /**
3025
3288
  * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
3026
- * analytics report already returns the team in one call — one row per logged session across all
3027
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
3028
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
3289
+ * analytics report returns one row per logged session across all `athleteIds`; `queryAnalytics`
3290
+ * splits oversized requests and merges those rows before this function groups them by athlete,
3291
+ * sums volume/reps, counts sessions, and rolls the athletes up into a team total. Athletes who
3029
3292
  * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
3030
3293
  * all-time `fetchRosterActivity` snapshot, which has no date range.
3031
3294
  */
@@ -3149,6 +3412,7 @@ function classifyMainLift(title) {
3149
3412
  return null;
3150
3413
  }
3151
3414
  const DEFAULT_MONTHS = 12;
3415
+ const WORKOUT_RANGE_DAYS = 180;
3152
3416
  function pad2(n) {
3153
3417
  return String(n).padStart(2, "0");
3154
3418
  }
@@ -3166,12 +3430,18 @@ function isoDay(d) {
3166
3430
  */
3167
3431
  async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3168
3432
  const months = opts.months ?? DEFAULT_MONTHS;
3433
+ if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
3169
3434
  const now = opts.now ?? /* @__PURE__ */ new Date();
3170
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
3435
+ const startDay = isoDay(new Date(now.getFullYear(), now.getMonth() - (months - 1), 1));
3436
+ const endDay = isoDay(now);
3437
+ const windows = splitDateRange(startDay, endDay, WORKOUT_RANGE_DAYS) ?? [{
3438
+ start: startDay,
3439
+ end: endDay
3440
+ }];
3171
3441
  const tally = /* @__PURE__ */ new Map();
3172
3442
  let workouts = [];
3173
3443
  try {
3174
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
3444
+ for (const window of windows) workouts.push(...await fetchCoachAthleteWorkouts(client, athleteId, window.start, window.end));
3175
3445
  } catch {
3176
3446
  workouts = [];
3177
3447
  }
@@ -3514,7 +3784,9 @@ var ExerciseLibrary = class {
3514
3784
  };
3515
3785
  }
3516
3786
  async create(body) {
3517
- return this.#writeThrough(CREATE_PATH, body, "create");
3787
+ const requestBody = { ...body };
3788
+ if (requestBody.points_of_performance === void 0) requestBody.points_of_performance = "";
3789
+ return this.#writeThrough(CREATE_PATH, requestBody, "create");
3518
3790
  }
3519
3791
  async update(id, body) {
3520
3792
  return this.#writeThrough(UPDATE_PATH(id), body, "update");
@@ -3522,7 +3794,7 @@ var ExerciseLibrary = class {
3522
3794
  async #writeThrough(path, body, label) {
3523
3795
  await this.ensureFresh();
3524
3796
  const res = await this.#client.request("POST", path, { body });
3525
- if (!res.ok) throw new Error(`Exercise ${label} failed (HTTP ${res.status}).`);
3797
+ if (!res.ok) throw new Error(trainHeroicApiErrorMessage(`Exercise ${label}`, res.status, res.data));
3526
3798
  const ex = unwrapEnvelope(res.data);
3527
3799
  if (ex && typeof ex === "object") {
3528
3800
  checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
@@ -3559,4 +3831,4 @@ var ExerciseLibrary = class {
3559
3831
  }
3560
3832
  };
3561
3833
  //#endregion
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 };
3834
+ 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, trainHeroicApiErrorMessage, unitAdvisory, unitLabel, unwrapEnvelope, updateTeam, updateTeamPublishSettings, withUnits, workoutsToCsv, workoutsToJson, workoutsToText };