@trainheroic-unofficial/js 3.6.0 → 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,12 +2,47 @@ 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
40
  const MAX_REQUEST_KEYS = 50;
7
41
  const MAX_RESPONSE_DEPTH = 4;
8
42
  const MAX_RESPONSE_KEYS = 20;
9
43
  const MAX_RESPONSE_ITEMS = 10;
10
44
  const MAX_RESPONSE_NODES = 50;
45
+ const MAX_RESPONSE_STRING = 2e3;
11
46
  const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
12
47
  "code",
13
48
  "detail",
@@ -45,6 +80,11 @@ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
45
80
  14,
46
81
  18
47
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
+ }
48
88
  function safeFieldName(key) {
49
89
  if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
50
90
  if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
@@ -72,17 +112,22 @@ function requestBodySummary(body) {
72
112
  const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
73
113
  const keys = entries.map(([key]) => safeFieldName(key));
74
114
  const values = {};
115
+ const arrayLengths = {};
75
116
  for (const [key, value] of entries) {
76
117
  const safeValue = safeRequestValue(key, value);
77
118
  if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
119
+ if (Array.isArray(value)) arrayLengths[safeFieldName(key)] = value.length;
78
120
  }
79
- return Object.keys(values).length > 0 ? {
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 {
80
126
  type: "object",
81
127
  keys,
82
- values
83
- } : {
84
- type: "object",
85
- keys
128
+ ...Object.keys(values).length > 0 ? { values } : {},
129
+ ...Object.keys(arrayLengths).length > 0 ? { arrayLengths } : {},
130
+ ...span === null ? {} : { dateSpanDays: span }
86
131
  };
87
132
  }
88
133
  const primitive = typeof body;
@@ -94,7 +139,7 @@ function sanitizedDiagnosticValue(value, depth, budget, field) {
94
139
  if (value === null) return null;
95
140
  if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
96
141
  if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
97
- if (typeof value === "string") return "[Redacted]";
142
+ if (typeof value === "string") return redactText(value);
98
143
  if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
99
144
  if (Array.isArray(value)) {
100
145
  const result = [];
@@ -173,6 +218,12 @@ function safeResponseBodyDiagnostics(body) {
173
218
  return "[Unavailable]";
174
219
  }
175
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
+ }
176
227
  /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
177
228
  var TrainHeroicHttpError = class extends Error {
178
229
  name = "TrainHeroicHttpError";
@@ -200,6 +251,9 @@ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
200
251
  } catch {}
201
252
  }
202
253
  //#endregion
254
+ //#region src/transport.ts
255
+ const defaultTrainHeroicTransport = (url, init) => fetch(url, init);
256
+ //#endregion
203
257
  //#region src/auth.ts
204
258
  const DEFAULT_AUTH_URL = "https://apis.trainheroic.com/auth";
205
259
  /**
@@ -223,7 +277,7 @@ function authUrl() {
223
277
  */
224
278
  async function loginTrainHeroic(email, password, options = {}) {
225
279
  const url = authUrl();
226
- const res = await fetch(url, {
280
+ const res = await (options.transport ?? defaultTrainHeroicTransport)(url, {
227
281
  method: "POST",
228
282
  headers: {
229
283
  "content-type": "application/x-www-form-urlencoded",
@@ -235,6 +289,7 @@ async function loginTrainHeroic(email, password, options = {}) {
235
289
  }).toString()
236
290
  });
237
291
  if (!res.ok) {
292
+ await res.body?.cancel().catch(() => {});
238
293
  notifyHttpError(options.onHttpError, "POST", url, res.status);
239
294
  return null;
240
295
  }
@@ -248,129 +303,6 @@ async function loginTrainHeroic(email, password, options = {}) {
248
303
  };
249
304
  }
250
305
  //#endregion
251
- //#region src/client.ts
252
- const DEFAULT_COACH_BASE = "https://api.trainheroic.com";
253
- const DEFAULT_APIS_BASE = "https://apis.trainheroic.com";
254
- /**
255
- * Resolve an API host, allowing an env override. The override exists so a test harness can point
256
- * the client at a local fake backend (and it doubles as a staging knob); production leaves these
257
- * unset and gets the real hosts. Read through `globalThis.process?.env` — not an `import process`
258
- * — so the runtime-agnostic `.` entry stays free of `node:*` and runs unchanged on workerd, and
259
- * read per request (not at module load) so a value the harness sets in the child env always wins.
260
- */
261
- function envBase(key, fallback) {
262
- const v = (globalThis.process?.env)?.[key];
263
- return v && v.length > 0 ? v : fallback;
264
- }
265
- var TrainHeroicAuthError = class extends Error {
266
- name = "TrainHeroicAuthError";
267
- };
268
- /**
269
- * Authenticated TrainHeroic API client. Holds the credentials (on the hosted Worker, from the
270
- * grant's encrypted props) and a lazily-acquired session token cached in memory for the life of
271
- * *this client instance* — nothing longer. On a 401/403 it re-logs in once and retries, since
272
- * TrainHeroic has no refresh token and sessions expire after ~1-2h.
273
- *
274
- * Anything that wants a session to outlive one client owns that itself: pass a previously
275
- * acquired token as `sessionId` and keep the new one via `options.onSession`. That matters
276
- * wherever clients are short-lived — the hosted Worker builds one per HTTP request, and each CLI
277
- * invocation is a fresh process — because otherwise every operation replays the password.
278
- */
279
- var TrainHeroicClient = class {
280
- #email;
281
- #password;
282
- #onSession;
283
- #onHttpError;
284
- #sessionId;
285
- #loginInFlight = null;
286
- constructor(email, password, sessionId = null, options = {}) {
287
- this.#email = email;
288
- this.#password = password;
289
- this.#sessionId = sessionId;
290
- this.#onSession = options.onSession;
291
- this.#onHttpError = options.onHttpError;
292
- }
293
- get sessionId() {
294
- return this.#sessionId;
295
- }
296
- async #ensureSession() {
297
- if (this.#sessionId) return this.#sessionId;
298
- this.#loginInFlight ??= this.#login();
299
- try {
300
- return await this.#loginInFlight;
301
- } finally {
302
- this.#loginInFlight = null;
303
- }
304
- }
305
- async #login() {
306
- const session = await loginTrainHeroic(this.#email, this.#password, this.#onHttpError ? { onHttpError: this.#onHttpError } : {});
307
- if (!session) throw new TrainHeroicAuthError("TrainHeroic login failed");
308
- this.#sessionId = session.sessionId;
309
- try {
310
- this.#onSession?.(this.#sessionId);
311
- } catch {}
312
- return this.#sessionId;
313
- }
314
- async request(method, path, options = {}) {
315
- const url = `${options.base === "apis" ? envBase("TH_APIS_BASE", DEFAULT_APIS_BASE) : envBase("TH_COACH_BASE", DEFAULT_COACH_BASE)}/${path.replace(/^\//, "")}`;
316
- let session = await this.#ensureSession();
317
- let res = await this.#send(method, url, session, options.body);
318
- if (res.status === 401 || res.status === 403) {
319
- if (this.#sessionId === session) this.#sessionId = null;
320
- session = await this.#ensureSession();
321
- res = await this.#send(method, url, session, options.body);
322
- }
323
- const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
324
- let text;
325
- try {
326
- text = await res.text();
327
- } catch (error) {
328
- if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
329
- throw error;
330
- }
331
- const data = parseResponseText(text);
332
- if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
333
- requestBody: options.body,
334
- responseBody: data
335
- });
336
- return {
337
- status: res.status,
338
- ok: res.ok,
339
- data
340
- };
341
- }
342
- #send(method, url, session, body) {
343
- const upper = method.toUpperCase();
344
- const headers = {
345
- accept: "application/json",
346
- "session-token": session
347
- };
348
- const init = {
349
- method: upper,
350
- headers
351
- };
352
- if (body !== void 0 && upper !== "GET" && upper !== "DELETE") {
353
- headers["content-type"] = "application/json";
354
- init.body = JSON.stringify(body);
355
- }
356
- return fetch(url, init);
357
- }
358
- };
359
- //#endregion
360
- //#region src/response-check.ts
361
- /**
362
- * Validate an API response against its (loose) expected shape and warn once on drift.
363
- * Never throws: callers keep working via defensive coercion. This only surfaces a signal
364
- * when TrainHeroic renames or drops a field we read.
365
- */
366
- function checkResponse(schema, data, label) {
367
- const result = schema.safeParse(data);
368
- if (result.success) return;
369
- const issue = result.error.issues[0];
370
- const where = issue && issue.path.length > 0 ? issue.path.join(".") : "(root)";
371
- console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
372
- }
373
- //#endregion
374
306
  //#region src/exercise-util.ts
375
307
  /**
376
308
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -623,6 +555,141 @@ function assertPositiveInteger(value, label) {
623
555
  if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
624
556
  }
625
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
626
693
  //#region src/athlete.ts
627
694
  async function getJson(client, path, label) {
628
695
  const res = await client.request("GET", path);
@@ -750,27 +817,9 @@ async function programWorkoutOnDate(client, date, programWorkoutId) {
750
817
  if (target === void 0) throw new Error(`No workout with id ${programWorkoutId} on ${date}. Get the id and date from athlete_workouts.`);
751
818
  return target;
752
819
  }
753
- /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
754
- function shiftDate(iso, days) {
755
- const d = /* @__PURE__ */ new Date(`${iso}T00:00:00Z`);
756
- d.setUTCDate(d.getUTCDate() + days);
757
- return d.toISOString().slice(0, 10);
758
- }
759
- /** 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. */
760
821
  function dateWindows(startDate, endDate, windowDays) {
761
- const size = Math.max(1, Math.floor(windowDays));
762
- const windows = [];
763
- let cursor = startDate;
764
- while (cursor <= endDate) {
765
- const winEnd = shiftDate(cursor, size - 1);
766
- const clamped = winEnd > endDate ? endDate : winEnd;
767
- windows.push({
768
- start: cursor,
769
- end: clamped
770
- });
771
- cursor = shiftDate(clamped, 1);
772
- }
773
- return windows;
822
+ return splitDateRange(startDate, endDate, Math.max(1, Math.floor(windowDays))) ?? [];
774
823
  }
775
824
  /**
776
825
  * Merge windowed pages of workouts into one list: deduped by workout id (a session sitting on a
@@ -3138,12 +3187,15 @@ const ANALYTICS_BODY_KEY = {
3138
3187
  exerciseId: "exercise_id",
3139
3188
  useMetric: "use_metric"
3140
3189
  };
3190
+ const TRAINING_SUMMARY_USER_BATCH = 5;
3191
+ const TRAINING_SUMMARY_RANGE_DAYS = 90;
3192
+ const MAX_TRAINING_SUMMARY_REQUESTS = 100;
3141
3193
  /**
3142
3194
  * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
3143
3195
  * athlete metrics need one or more `userIds` (passed together — the report returns a row per
3144
3196
  * athlete). Throws a readable Error when a required input is missing or the call fails.
3145
3197
  */
3146
- async function queryAnalytics(client, args) {
3198
+ async function requestAnalytics(client, args) {
3147
3199
  const spec = ANALYTICS_METRICS[args.metric];
3148
3200
  const body = {};
3149
3201
  if (spec.scope === "team") {
@@ -3171,6 +3223,42 @@ async function queryAnalytics(client, args) {
3171
3223
  if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
3172
3224
  return res.data;
3173
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
+ }
3174
3262
  /**
3175
3263
  * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
3176
3264
  * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
@@ -3198,9 +3286,9 @@ function toNum(v) {
3198
3286
  }
3199
3287
  /**
3200
3288
  * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
3201
- * analytics report already returns the team in one call — one row per logged session across all
3202
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
3203
- * 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
3204
3292
  * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
3205
3293
  * all-time `fetchRosterActivity` snapshot, which has no date range.
3206
3294
  */
@@ -3324,6 +3412,7 @@ function classifyMainLift(title) {
3324
3412
  return null;
3325
3413
  }
3326
3414
  const DEFAULT_MONTHS = 12;
3415
+ const WORKOUT_RANGE_DAYS = 180;
3327
3416
  function pad2(n) {
3328
3417
  return String(n).padStart(2, "0");
3329
3418
  }
@@ -3341,12 +3430,18 @@ function isoDay(d) {
3341
3430
  */
3342
3431
  async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3343
3432
  const months = opts.months ?? DEFAULT_MONTHS;
3433
+ if (!Number.isSafeInteger(months) || months < 1) throw new RangeError("months must be a positive integer.");
3344
3434
  const now = opts.now ?? /* @__PURE__ */ new Date();
3345
- 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
+ }];
3346
3441
  const tally = /* @__PURE__ */ new Map();
3347
3442
  let workouts = [];
3348
3443
  try {
3349
- 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));
3350
3445
  } catch {
3351
3446
  workouts = [];
3352
3447
  }
@@ -3689,7 +3784,9 @@ var ExerciseLibrary = class {
3689
3784
  };
3690
3785
  }
3691
3786
  async create(body) {
3692
- 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");
3693
3790
  }
3694
3791
  async update(id, body) {
3695
3792
  return this.#writeThrough(UPDATE_PATH(id), body, "update");
@@ -3697,7 +3794,7 @@ var ExerciseLibrary = class {
3697
3794
  async #writeThrough(path, body, label) {
3698
3795
  await this.ensureFresh();
3699
3796
  const res = await this.#client.request("POST", path, { body });
3700
- 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));
3701
3798
  const ex = unwrapEnvelope(res.data);
3702
3799
  if (ex && typeof ex === "object") {
3703
3800
  checkResponse(exerciseResponseSchema, ex, `exercise ${label}`);
@@ -3734,4 +3831,4 @@ var ExerciseLibrary = class {
3734
3831
  }
3735
3832
  };
3736
3833
  //#endregion
3737
- 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 };
package/dist/node.d.mts CHANGED
@@ -1,13 +1,12 @@
1
1
  import { n as LibrarySnapshot, t as LibraryCache } from "./library-cache-CDABOdIN.mjs";
2
2
  //#region src/node.d.ts
3
3
  /** Default exercise-cache path, overridable with TRAINHEROIC_CACHE_FILE. */
4
- declare function defaultCachePath(): string;
4
+ export declare function defaultCachePath(): string;
5
5
  /** Persists the exercise library to a JSON file. */
6
- declare class JsonFileLibraryCache implements LibraryCache {
6
+ export declare class JsonFileLibraryCache implements LibraryCache {
7
7
  #private;
8
8
  constructor(path?: string);
9
9
  load(): Promise<LibrarySnapshot | null>;
10
10
  save(snapshot: LibrarySnapshot): Promise<void>;
11
11
  }
12
- //#endregion
13
- export { JsonFileLibraryCache, defaultCachePath };
12
+ //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "3.6.0",
3
+ "version": "3.7.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,12 +27,12 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "es-toolkit": "^1.52.0",
30
- "zod": "^4.4.3",
31
- "@trainheroic-unofficial/dto": "3.6.0"
30
+ "zod": "^4.6.3",
31
+ "@trainheroic-unofficial/dto": "3.7.1"
32
32
  },
33
33
  "devDependencies": {
34
- "@types/node": "^26.3.0",
35
- "tsdown": "^0.22.14",
34
+ "@types/node": "^26.5.1",
35
+ "tsdown": "^0.23.0",
36
36
  "vitest": "^4.1.11"
37
37
  },
38
38
  "scripts": {