@trainheroic-unofficial/js 0.4.2 → 0.5.0

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.
Files changed (2) hide show
  1. package/README.md +204 -7
  2. package/package.json +2 -2
package/README.md CHANGED
@@ -7,6 +7,108 @@ JavaScript runtime, including Cloudflare workerd.
7
7
 
8
8
  Part of the [trainheroic-unofficial](../../README.md) workspace.
9
9
 
10
+ > Unaffiliated with TrainHeroic. It drives the same undocumented endpoints the web app uses,
11
+ > so a server-side change can break it without warning. Use it against your own account.
12
+
13
+ ## Contents
14
+
15
+ - [Install](#install)
16
+ - [Quickstart](#quickstart)
17
+ - [Two entry points](#two-entry-points)
18
+ - [What it covers](#what-it-covers)
19
+ - [Working with exercises](#working-with-exercises)
20
+ - [Building a workout](#building-a-workout)
21
+ - [Reading athlete training](#reading-athlete-training)
22
+ - [The workout encoder](#the-workout-encoder)
23
+ - [Develop](#develop)
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ npm install @trainheroic-unofficial/js
29
+ # or: pnpm add @trainheroic-unofficial/js
30
+ ```
31
+
32
+ Requires a runtime with global `fetch` and Web Crypto (Node >= 18, workerd, modern browsers).
33
+
34
+ ## Quickstart
35
+
36
+ Construct a client with your TrainHeroic credentials and call `request`. The client logs in
37
+ lazily on the first call and renews the session for you.
38
+
39
+ ```ts
40
+ import { TrainHeroicClient } from "@trainheroic-unofficial/js";
41
+
42
+ const client = new TrainHeroicClient(
43
+ process.env.TRAINHEROIC_EMAIL!,
44
+ process.env.TRAINHEROIC_PASSWORD!,
45
+ );
46
+
47
+ // request<T>(method, path, options) reaches any endpoint the web app uses.
48
+ // The type parameter T types res.data; omit it and data is `unknown`.
49
+ const res = await client.request<{ id: number }>("GET", "/user/simple");
50
+ if (res.ok) {
51
+ console.log(res.data.id);
52
+ }
53
+ ```
54
+
55
+ `request` returns `{ status: number; ok: boolean; data: T }`. It does not throw on an HTTP
56
+ error status, so check `res.ok`. It throws `TrainHeroicAuthError` only when a login attempt
57
+ fails (bad credentials).
58
+
59
+ The third argument, `options`, is `RequestOptions`:
60
+
61
+ ```ts
62
+ type RequestOptions = {
63
+ body?: unknown; // serialized as JSON for non-GET/DELETE requests
64
+ base?: "coach" | "apis"; // which host; defaults to "coach" (api.trainheroic.com)
65
+ };
66
+ ```
67
+
68
+ So a write is the same call with a body:
69
+
70
+ ```ts
71
+ const created = await client.request("POST", "/2.0/coach/exercise/create", {
72
+ body: { title: "Sled Push" },
73
+ });
74
+ ```
75
+
76
+ There is no enumerated endpoint catalog; the paths are the ones the TrainHeroic web app calls.
77
+ Most are reachable through the typed helpers below, so you rarely call `request` directly. The
78
+ request and response shapes those helpers use live in
79
+ [`@trainheroic-unofficial/dto`](../dto) as zod schemas and types.
80
+
81
+ ### Reusing a session across restarts
82
+
83
+ TrainHeroic has no refresh token and a session expires after roughly one or two hours. By
84
+ default the client logs in on its first request and keeps the session token in memory for the
85
+ life of the process, so a fresh process logs in again. To skip that login, read the token off
86
+ one client and hand it to the next via the third constructor argument.
87
+
88
+ After a request has run, `client.sessionId` holds the active token, typed `string | null` (it
89
+ is `null` only before the first login). Persist it with your own storage — `saveToken` and
90
+ `loadToken` below stand in for whatever you use (a file, a KV store, an env var):
91
+
92
+ ```ts
93
+ await client.request("GET", "/user/simple");
94
+ const token = client.sessionId;
95
+ if (token) saveToken(token);
96
+ ```
97
+
98
+ A later process passes the saved token as the third constructor argument (also `string | null`,
99
+ so a missing token simply falls back to a normal login):
100
+
101
+ ```ts
102
+ const client = new TrainHeroicClient(
103
+ process.env.TRAINHEROIC_EMAIL!,
104
+ process.env.TRAINHEROIC_PASSWORD!,
105
+ loadToken(),
106
+ );
107
+ ```
108
+
109
+ If the reused token has expired, the next request gets a 401/403; the client logs in once with
110
+ the credentials, retries, and updates `client.sessionId` to the new token.
111
+
10
112
  ## Two entry points
11
113
 
12
114
  ```ts
@@ -18,7 +120,7 @@ import { JsonFileLibraryCache, defaultCachePath } from "@trainheroic-unofficial/
18
120
  ```
19
121
 
20
122
  The `.` entry imports no `node:*` modules. Anything that touches the filesystem lives behind
21
- `./node`, so the SDK stays portable.
123
+ `./node`.
22
124
 
23
125
  ## What it covers
24
126
 
@@ -34,20 +136,111 @@ The `.` entry imports no `node:*` modules. Anything that touches the filesystem
34
136
  - **Workouts.** A session builder (create, save blocks and exercises, optionally publish),
35
137
  read-back, instruction editing, and removal, plus the encoder that turns a
36
138
  `WorkoutSpec` into the API's payload.
139
+ - **Athlete training.** Functions for the logged-in account's own training: scheduled and
140
+ completed workouts, per-exercise history, personal records, and working maxes.
37
141
  - **Messaging.** Listing conversation streams, reading a stream, and building, sending, or
38
142
  deleting a comment.
39
143
 
144
+ ## Working with exercises
145
+
146
+ `ExerciseLibrary` loads the full library once, caches it, and answers name lookups and fuzzy
147
+ search against the in-memory copy. By default it caches in memory; pass a `JsonFileLibraryCache`
148
+ from `./node` to persist between runs (it writes to `defaultCachePath()`,
149
+ `~/.trainheroic/library.json`, unless you pass a path).
150
+
151
+ ```ts
152
+ import { ExerciseLibrary } from "@trainheroic-unofficial/js";
153
+ import { JsonFileLibraryCache } from "@trainheroic-unofficial/js/node";
154
+
155
+ // `client` is the TrainHeroicClient from the Quickstart above.
156
+ const library = new ExerciseLibrary(client, new JsonFileLibraryCache());
157
+
158
+ // Fuzzy search, ranked. Returns up to `limit` matches, each with id, title, and units.
159
+ const matches = await library.search("back squat", 5);
160
+
161
+ // resolve() returns { match, candidates }. A single confident hit fills `match`;
162
+ // an ambiguous name leaves `match` null and returns the candidates to choose from.
163
+ const { match, candidates } = await library.resolve("Barbell Back Squat");
164
+ if (!match) {
165
+ // Ask the user (or the model) to pick one of `candidates`, then use its id.
166
+ console.log(candidates.map((c) => `${c.id}: ${c.title}`));
167
+ }
168
+ ```
169
+
170
+ ## Building a workout
171
+
172
+ `buildSession` writes one session into a program on a given day: it creates the session, saves
173
+ the blocks and exercises, and optionally publishes. `programId` identifies one of your
174
+ TrainHeroic programs — find it in the program's URL in the web app, or from a programs read
175
+ (`client.request("GET", ...)`). Exercise ids come from the library.
176
+
177
+ ```ts
178
+ import { buildSession, type BlockSpec } from "@trainheroic-unofficial/js";
179
+
180
+ const { match } = await library.resolve("Back Squat");
181
+ if (!match) throw new Error("Resolve to a single exercise before building.");
182
+
183
+ const blocks: BlockSpec[] = [
184
+ {
185
+ title: "Strength",
186
+ exercises: [
187
+ // sets/reps/weight scalars; rpe is routed into the instruction text (see the encoder).
188
+ { id: match.id, sets: 5, reps: 5, weight: 225, rpe: 8 },
189
+ ],
190
+ },
191
+ ];
192
+
193
+ const { pwId, workoutId } = await buildSession(client, {
194
+ programId: 12345,
195
+ date: [2026, 6, 22], // [year, month, day]; month is 1-based, so 6 = June
196
+ blocks,
197
+ instruction: "Warm up first.",
198
+ publish: false, // build as a draft; publish makes it visible to athletes
199
+ });
200
+ ```
201
+
202
+ Each exercise needs an `id`; `sets`, `reps`, `weight`, `rpe`, and a per-exercise `instr` are
203
+ optional. `reps` and `weight` take a scalar (broadcast across every set) or a per-set array
204
+ like `reps: [5, 5, 3]`. The full field list is `ExerciseSpec` / `BlockSpec` in
205
+ [`@trainheroic-unofficial/dto`](../dto). Loads are in whatever unit the exercise is configured
206
+ for in TrainHeroic; a mismatch becomes an advisory rather than a silent change (below).
207
+
208
+ `buildSession` returns `{ pwId, workoutId }`: `pwId` is the program-workout id (the placement
209
+ of the session in the program — this is the handle the other calls take), and `workoutId` is
210
+ the underlying workout id. Read it back with `readSession(client, programId, date, pwId)`,
211
+ publish later with `publishSession(client, pwId)`, or remove it with
212
+ `removeSession(client, programId, pwId)`.
213
+
214
+ ## Reading athlete training
215
+
216
+ ```ts
217
+ import { resolveAthleteUserId, fetchAthleteProfileSummary } from "@trainheroic-unofficial/js";
218
+
219
+ const userId = await resolveAthleteUserId(client);
220
+ const summary = await fetchAthleteProfileSummary(client, userId);
221
+ ```
222
+
223
+ These work from any session, coach or athlete, since a coach account also carries athlete
224
+ scope.
225
+
40
226
  ## The workout encoder
41
227
 
42
- The encoder is the package's hardest-won piece. TrainHeroic's exercise payload expects every
43
- parameter slot present, so the encoder fills all of them (empty slots included) to avoid an
44
- HTTP 500. A scalar prescription is broadcast across the set count, RPE is routed into the
45
- instruction text rather than a numeric slot (the API would otherwise coerce it to load), and
46
- unit mismatches between a spec and the exercise's fixed parameter types are surfaced as
47
- advisories instead of silently dropped.
228
+ `buildSession` calls the encoder for you; you only deal with it directly to preview warnings.
229
+ TrainHeroic's exercise payload expects every parameter slot present, so the encoder fills all
230
+ of them (empty slots included) to avoid an HTTP 500. A scalar prescription is broadcast across
231
+ the set count, RPE is routed into the instruction text rather than a numeric slot (the API
232
+ would otherwise coerce it to load), and unit mismatches between a spec and the exercise's fixed
233
+ parameter types are collected as advisories rather than silently dropped.
234
+
235
+ Those advisories are not part of the `buildSession` result; read them before building by
236
+ calling `collectAdvisories(blocks, index)` (the `index` is an `ExerciseLibrary`), which returns
237
+ the unit notes and warnings for a set of blocks.
48
238
 
49
239
  ## Develop
50
240
 
241
+ Clone the workspace and run `pnpm install` once at the repo root (Node >= 22, pnpm 10), then
242
+ from this package directory:
243
+
51
244
  ```bash
52
245
  pnpm build # tsdown -> dist (separate "." and "./node" outputs)
53
246
  pnpm typecheck
@@ -55,3 +248,7 @@ pnpm test
55
248
  pnpm exec vitest run test/workout-encode.test.ts # one file
56
249
  pnpm exec vitest run -t "broadcasts a scalar over sets" # one test
57
250
  ```
251
+
252
+ ## License
253
+
254
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/js",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "dependencies": {
29
29
  "zod": "^4.4.3",
30
- "@trainheroic-unofficial/dto": "0.4.2"
30
+ "@trainheroic-unofficial/dto": "0.5.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^26.0.0",