@dlwiest/ts-tonal-client 0.0.1 → 0.1.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.
Files changed (48) hide show
  1. package/README.md +413 -37
  2. package/dist/examples/create-workout.d.ts +1 -0
  3. package/dist/examples/debug-daily-lifts.d.ts +1 -0
  4. package/dist/examples/delete-workout.d.ts +1 -0
  5. package/dist/examples/edit-workout.d.ts +1 -0
  6. package/dist/examples/estimate-workout.d.ts +1 -0
  7. package/dist/examples/get-achievement-stats.d.ts +2 -0
  8. package/dist/examples/get-achievements.d.ts +2 -0
  9. package/dist/examples/get-activity-summaries.d.ts +2 -0
  10. package/dist/examples/get-current-streak.d.ts +1 -0
  11. package/dist/examples/get-daily-lifts.d.ts +1 -0
  12. package/dist/examples/get-daily-metrics.d.ts +1 -0
  13. package/dist/examples/get-goal-metrics.d.ts +1 -0
  14. package/dist/examples/get-goals.d.ts +1 -0
  15. package/dist/examples/get-home-calendar.d.ts +2 -0
  16. package/dist/examples/get-metric-scores.d.ts +1 -0
  17. package/dist/examples/get-movements.d.ts +1 -0
  18. package/dist/examples/get-muscle-readiness.d.ts +1 -0
  19. package/dist/examples/get-program-by-id.d.ts +1 -0
  20. package/dist/examples/get-target-scores.d.ts +1 -0
  21. package/dist/examples/get-training-effect-goals.d.ts +1 -0
  22. package/dist/examples/get-training-types.d.ts +1 -0
  23. package/dist/examples/get-user-info.d.ts +1 -0
  24. package/dist/examples/get-user-settings.d.ts +1 -0
  25. package/dist/examples/get-user-statistics.d.ts +2 -0
  26. package/dist/examples/get-user-workouts.d.ts +1 -0
  27. package/dist/examples/get-workout-by-id.d.ts +1 -0
  28. package/dist/examples/get-workout-by-share-url.d.ts +1 -0
  29. package/dist/examples/raw-daily-lifts-test.d.ts +1 -0
  30. package/dist/index.d.ts +573 -29
  31. package/dist/index.esm.js +510 -118
  32. package/dist/index.js +514 -118
  33. package/dist/src/auth/auth-manager.d.ts +15 -0
  34. package/dist/src/client.d.ts +39 -0
  35. package/dist/src/http/http-client.d.ts +12 -0
  36. package/dist/src/index.d.ts +4 -0
  37. package/dist/src/services/movement-service.d.ts +7 -0
  38. package/dist/src/services/user-service.d.ts +51 -0
  39. package/dist/src/services/workout-service.d.ts +14 -0
  40. package/dist/src/types/auth.d.ts +18 -0
  41. package/dist/src/types/common.d.ts +1 -0
  42. package/dist/src/types/index.d.ts +6 -0
  43. package/dist/src/types/movements.d.ts +30 -0
  44. package/dist/src/types/programs.d.ts +46 -0
  45. package/dist/src/types/users.d.ts +418 -0
  46. package/dist/src/types/workouts.d.ts +120 -0
  47. package/dist/src/types.d.ts +125 -0
  48. package/package.json +54 -4
package/dist/index.esm.js CHANGED
@@ -1,147 +1,539 @@
1
- /******************************************************************************
2
- Copyright (c) Microsoft Corporation.
3
-
4
- Permission to use, copy, modify, and/or distribute this software for any
5
- purpose with or without fee is hereby granted.
6
-
7
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
- PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */
15
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
16
-
17
-
18
- function __awaiter(thisArg, _arguments, P, generator) {
19
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
20
- return new (P || (P = Promise))(function (resolve, reject) {
21
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
23
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
24
- step((generator = generator.apply(thisArg, _arguments || [])).next());
25
- });
26
- }
27
-
28
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
29
- var e = new Error(message);
30
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
31
- };
1
+ class TonalClientError extends Error {
2
+ constructor(message, statusCode, originalError) {
3
+ super(message);
4
+ this.name = 'TonalClientError';
5
+ this.statusCode = statusCode;
6
+ this.originalError = originalError;
7
+ }
8
+ }
32
9
 
33
- class TonalClient {
34
- constructor({ username, password }) {
35
- this.username = username;
36
- this.password = password;
10
+ class AuthManager {
11
+ constructor(username, password) {
37
12
  this.idToken = '';
13
+ this.refreshToken = '';
38
14
  this.tokenExpiresAt = 0;
15
+ this.isRefreshing = false;
16
+ this.authUrl = 'https://tonal.auth0.com/oauth/token';
17
+ this.clientId = 'ERCyexW-xoVG_Yy3RDe-eV4xsOnRHP6L';
18
+ this.username = username;
19
+ this.password = password;
39
20
  }
40
- // TonalClient factory
41
- static create(_a) {
42
- return __awaiter(this, arguments, void 0, function* ({ username, password }) {
43
- const client = new TonalClient({ username, password });
44
- yield client.refreshToken();
45
- return client;
46
- });
47
- }
48
- // Request a new ID token from Auth0
49
- refreshToken() {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- const data = {
21
+ async authenticate() {
22
+ if (this.isTokenValid()) {
23
+ return this.idToken;
24
+ }
25
+ const response = await fetch(this.authUrl, {
26
+ method: 'POST',
27
+ headers: {
28
+ 'Content-Type': 'application/json',
29
+ },
30
+ body: JSON.stringify({
52
31
  username: this.username,
53
32
  password: this.password,
54
- client_id: 'ERCyexW-xoVG_Yy3RDe-eV4xsOnRHP6L',
33
+ client_id: this.clientId,
55
34
  grant_type: 'password',
56
35
  scope: 'offline_access',
57
- };
36
+ }),
37
+ });
38
+ if (!response.ok) {
39
+ const errorText = await response.text();
40
+ let errorData;
58
41
  try {
59
- const response = yield fetch('https://tonal.auth0.com/oauth/token', {
60
- method: 'POST',
61
- headers: {
62
- 'Content-Type': 'application/json',
63
- },
64
- body: JSON.stringify(data),
65
- });
66
- if (response.status === 403) {
67
- throw new Error('Invalid username or password');
42
+ errorData = JSON.parse(errorText);
43
+ }
44
+ catch {
45
+ errorData = { error: errorText };
46
+ }
47
+ throw new TonalClientError(errorData.error_description || errorData.error || 'Authentication failed', response.status, errorData);
48
+ }
49
+ const tokenData = await response.json();
50
+ this.idToken = tokenData.id_token;
51
+ this.refreshToken = tokenData.refresh_token;
52
+ this.tokenExpiresAt = Date.now() + (tokenData.expires_in * 1000);
53
+ return this.idToken;
54
+ }
55
+ async getValidToken() {
56
+ if (this.isTokenValid()) {
57
+ return this.idToken;
58
+ }
59
+ if (this.refreshToken) {
60
+ if (!this.isRefreshing) {
61
+ await this.refreshTokens();
62
+ }
63
+ else {
64
+ // Wait for ongoing refresh to complete
65
+ while (this.isRefreshing) {
66
+ await new Promise(resolve => setTimeout(resolve, 100));
68
67
  }
69
- const json = (yield response.json());
70
- this.idToken = json.id_token;
71
- this.tokenExpiresAt = Date.now() + json.expires_in * 1000;
72
68
  }
73
- catch (e) {
74
- console.error(e);
75
- throw new Error('Failed to retrieve access token');
69
+ if (this.isTokenValid()) {
70
+ return this.idToken;
76
71
  }
77
- });
72
+ }
73
+ throw new TonalClientError('Token expired and refresh failed. Call authenticate() first.');
78
74
  }
79
- // Get all movements available on Tonal
80
- getMovements() {
81
- return __awaiter(this, void 0, void 0, function* () {
82
- try {
83
- if (this.tokenExpiresAt < Date.now()) {
84
- yield this.refreshToken();
75
+ isTokenValid() {
76
+ return !!this.idToken && Date.now() < this.tokenExpiresAt - 60000; // 1 minute buffer
77
+ }
78
+ async refreshTokens() {
79
+ if (this.isRefreshing) {
80
+ return; // Prevent concurrent refresh attempts
81
+ }
82
+ this.isRefreshing = true;
83
+ try {
84
+ const response = await fetch(this.authUrl, {
85
+ method: 'POST',
86
+ headers: {
87
+ 'Content-Type': 'application/json',
88
+ },
89
+ body: JSON.stringify({
90
+ client_id: this.clientId,
91
+ grant_type: 'refresh_token',
92
+ refresh_token: this.refreshToken,
93
+ }),
94
+ });
95
+ if (!response.ok) {
96
+ const errorText = await response.text();
97
+ let errorData;
98
+ try {
99
+ errorData = JSON.parse(errorText);
100
+ }
101
+ catch {
102
+ errorData = { error: errorText };
85
103
  }
86
- const response = yield fetch('https://api.tonal.com/v6/movements', {
87
- headers: {
88
- Authorization: `Bearer ${this.idToken}`,
89
- },
90
- });
91
- return (yield response.json());
104
+ throw new TonalClientError(errorData.error_description || errorData.error || 'Token refresh failed', response.status, errorData);
92
105
  }
93
- catch (e) {
94
- console.error(e);
95
- throw new Error('Failed to retrieve movements');
106
+ const tokenData = await response.json();
107
+ this.idToken = tokenData.id_token;
108
+ this.refreshToken = tokenData.refresh_token;
109
+ this.tokenExpiresAt = Date.now() + (tokenData.expires_in * 1000);
110
+ }
111
+ finally {
112
+ this.isRefreshing = false;
113
+ }
114
+ }
115
+ }
116
+
117
+ class HttpClient {
118
+ constructor(authManager) {
119
+ this.authManager = authManager;
120
+ this.baseUrl = 'https://api.tonal.com/v6';
121
+ this.requestTimeout = 30000;
122
+ this.maxRetries = 3;
123
+ }
124
+ async request(endpoint, options = {}, expectsBody = true) {
125
+ const url = `${this.baseUrl}${endpoint}`;
126
+ return this.makeRequestWithRetry(url, options, expectsBody);
127
+ }
128
+ async makeRequest(url, options = {}, expectsBody = true) {
129
+ const controller = new AbortController();
130
+ const timeoutId = setTimeout(() => controller.abort(), this.requestTimeout);
131
+ try {
132
+ const token = await this.authManager.getValidToken();
133
+ const response = await fetch(url, {
134
+ ...options,
135
+ headers: {
136
+ Authorization: `Bearer ${token}`,
137
+ 'Content-Type': 'application/json',
138
+ ...options.headers,
139
+ },
140
+ signal: controller.signal,
141
+ });
142
+ clearTimeout(timeoutId);
143
+ if (!response.ok) {
144
+ const errorText = await response.text();
145
+ let errorData;
146
+ try {
147
+ errorData = JSON.parse(errorText);
148
+ }
149
+ catch {
150
+ errorData = { error: errorText };
151
+ }
152
+ throw new TonalClientError(errorData.error_description || errorData.error || `HTTP ${response.status}`, response.status, errorData);
96
153
  }
97
- });
154
+ if (expectsBody) {
155
+ return await response.json();
156
+ }
157
+ else {
158
+ return undefined;
159
+ }
160
+ }
161
+ catch (error) {
162
+ clearTimeout(timeoutId);
163
+ if (error instanceof TonalClientError) {
164
+ throw error;
165
+ }
166
+ if (error instanceof Error && error.name === 'AbortError') {
167
+ throw new TonalClientError('Request timeout', undefined, error);
168
+ }
169
+ throw new TonalClientError('Request failed', undefined, error);
170
+ }
98
171
  }
99
- // Get a workout by its ID
100
- getWorkoutById(id) {
101
- return __awaiter(this, void 0, void 0, function* () {
172
+ async makeRequestWithRetry(url, options = {}, expectsBody = true) {
173
+ let lastError;
174
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
102
175
  try {
103
- if (this.tokenExpiresAt < Date.now()) {
104
- yield this.refreshToken();
105
- }
106
- const response = yield fetch(`https://api.tonal.com/v6/workouts/${id}`, {
107
- headers: {
108
- Authorization: `Bearer ${this.idToken}`,
109
- },
110
- });
111
- const json = (yield response.json());
112
- return json;
176
+ return await this.makeRequest(url, options, expectsBody);
113
177
  }
114
- catch (e) {
115
- console.error(e);
116
- throw new Error('Failed to retrieve workout');
178
+ catch (error) {
179
+ lastError = error instanceof TonalClientError ? error : new TonalClientError('Unknown error', undefined, error);
180
+ // If it's an auth error on first attempt, try to refresh token and retry once
181
+ if (attempt === 1 && lastError.statusCode && (lastError.statusCode === 401 || lastError.statusCode === 403)) {
182
+ try {
183
+ await this.authManager.getValidToken(); // This will refresh if needed
184
+ continue; // Retry the request with the new token
185
+ }
186
+ catch (refreshError) {
187
+ // If refresh fails, continue with normal retry logic
188
+ }
189
+ }
190
+ if (attempt === this.maxRetries || (lastError.statusCode && lastError.statusCode < 500)) {
191
+ throw lastError;
192
+ }
193
+ const delay = Math.pow(2, attempt - 1) * 1000;
194
+ await this.sleep(delay);
117
195
  }
196
+ }
197
+ throw lastError;
198
+ }
199
+ async sleep(ms) {
200
+ return new Promise(resolve => setTimeout(resolve, ms));
201
+ }
202
+ }
203
+
204
+ class WorkoutService {
205
+ constructor(httpClient) {
206
+ this.httpClient = httpClient;
207
+ }
208
+ async getUserWorkouts(offset = 0, limit = 50) {
209
+ return this.httpClient.request('/user-workouts', {
210
+ method: 'GET',
211
+ headers: {
212
+ 'x-paginate-offset': offset.toString(),
213
+ 'x-paginate-limit': limit.toString(),
214
+ },
118
215
  });
119
216
  }
120
- // Get a workout by its share URL
121
- getWorkoutByShareUrl(shareUrl) {
122
- return __awaiter(this, void 0, void 0, function* () {
123
- if (!shareUrl) {
124
- throw new Error('Share URL is required');
125
- }
126
- const shareId = shareUrl.split('/').pop();
217
+ async getDailyLifts(userInfo, timeZone) {
218
+ const device = userInfo.recentMobileDevice;
219
+ const userAgent = device.platform === 'ios'
220
+ ? `Tonal/3004226 CFNetwork/3860.100.1 Darwin/${device.osVersion}`
221
+ : `Tonal/${device.appVersion}`;
222
+ // Use provided timezone, or auto-detect from system, or fall back to UTC
223
+ let detectedTimeZone = timeZone;
224
+ if (!detectedTimeZone) {
127
225
  try {
128
- if (this.tokenExpiresAt < Date.now()) {
129
- yield this.refreshToken();
130
- }
131
- const response = yield fetch(`https://api.tonal.com/v6/user-workouts/sharing-records/${shareId}`, {
132
- headers: {
133
- Authorization: `Bearer ${this.idToken}`,
134
- },
135
- });
136
- const json = (yield response.json());
137
- return json;
226
+ detectedTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
138
227
  }
139
- catch (e) {
140
- console.error(e);
141
- throw new Error('Failed to retrieve workout');
228
+ catch {
229
+ detectedTimeZone = 'UTC';
142
230
  }
231
+ }
232
+ return this.httpClient.request(`/user-workouts?types=DailyLift`, {
233
+ method: 'GET',
234
+ headers: {
235
+ 'Time-Zone': detectedTimeZone,
236
+ 'AppVersion': device.appVersion,
237
+ 'DeviceId': device.tonalDeviceId,
238
+ 'Accept': '*/*',
239
+ 'Accept-Encoding': 'gzip, deflate, br',
240
+ 'Accept-Language': 'en-US,en;q=0.9',
241
+ 'User-Agent': userAgent,
242
+ },
143
243
  });
144
244
  }
245
+ async getWorkoutById(workoutId) {
246
+ if (!workoutId?.trim()) {
247
+ throw new TonalClientError('Workout ID is required');
248
+ }
249
+ return this.httpClient.request(`/workouts/${workoutId}`);
250
+ }
251
+ async getWorkoutByShareUrl(shareUrl) {
252
+ if (!shareUrl?.trim()) {
253
+ throw new TonalClientError('Share URL is required');
254
+ }
255
+ const urlPattern = /https:\/\/share\.tonal\.com\/workout\/([a-f0-9-]+)/;
256
+ const match = shareUrl.match(urlPattern);
257
+ if (!match) {
258
+ throw new TonalClientError('Invalid share URL format. Expected: https://share.tonal.com/workout/{id}');
259
+ }
260
+ const shareId = match[1];
261
+ return this.httpClient.request(`/user-workouts/sharing-records/${encodeURIComponent(shareId)}`);
262
+ }
263
+ async estimateWorkoutDuration(sets) {
264
+ if (!sets?.length) {
265
+ throw new TonalClientError('At least one set is required for estimation');
266
+ }
267
+ return this.httpClient.request('/user-workouts/estimate', {
268
+ method: 'POST',
269
+ body: JSON.stringify({ sets }),
270
+ });
271
+ }
272
+ async createWorkout(workoutData) {
273
+ if (!workoutData.title?.trim()) {
274
+ throw new TonalClientError('Workout title is required');
275
+ }
276
+ if (!workoutData.sets?.length) {
277
+ throw new TonalClientError('At least one set is required');
278
+ }
279
+ const requestBody = {
280
+ title: workoutData.title,
281
+ sets: workoutData.sets,
282
+ createdSource: workoutData.createdSource || 'WorkoutBuilder',
283
+ shortDescription: workoutData.shortDescription || '',
284
+ description: workoutData.description || '',
285
+ };
286
+ return this.httpClient.request('/user-workouts', {
287
+ method: 'POST',
288
+ body: JSON.stringify(requestBody),
289
+ });
290
+ }
291
+ async updateWorkout(workoutData) {
292
+ if (!workoutData.id) {
293
+ throw new TonalClientError('Workout ID is required for updates');
294
+ }
295
+ if (!workoutData.title?.trim()) {
296
+ throw new TonalClientError('Workout title is required');
297
+ }
298
+ if (!workoutData.sets?.length) {
299
+ throw new TonalClientError('At least one set is required');
300
+ }
301
+ const requestBody = {
302
+ id: workoutData.id,
303
+ title: workoutData.title,
304
+ description: workoutData.description || '',
305
+ coachId: workoutData.coachId || '00000000-0000-0000-0000-000000000000',
306
+ sets: workoutData.sets,
307
+ level: workoutData.level || '',
308
+ assetId: workoutData.assetId,
309
+ createdSource: workoutData.createdSource || 'WorkoutBuilder'
310
+ };
311
+ return this.httpClient.request(`/user-workouts/${workoutData.id}`, {
312
+ method: 'PUT',
313
+ body: JSON.stringify(requestBody),
314
+ });
315
+ }
316
+ async deleteWorkout(workoutId) {
317
+ if (!workoutId?.trim()) {
318
+ throw new TonalClientError('Workout ID is required');
319
+ }
320
+ await this.httpClient.request(`/user-workouts/${workoutId}`, {
321
+ method: 'DELETE',
322
+ }, false);
323
+ }
324
+ }
325
+
326
+ class MovementService {
327
+ constructor(httpClient) {
328
+ this.httpClient = httpClient;
329
+ }
330
+ async getMovements() {
331
+ return this.httpClient.request('/movements');
332
+ }
333
+ }
334
+
335
+ class UserService {
336
+ constructor(httpClient) {
337
+ this.httpClient = httpClient;
338
+ }
339
+ async getUserInfo() {
340
+ return this.httpClient.request('/users/userinfo');
341
+ }
342
+ async getGoals() {
343
+ return this.httpClient.request('/goals');
344
+ }
345
+ async getTrainingEffectGoals() {
346
+ return this.httpClient.request('/training-effect-goals');
347
+ }
348
+ async getTrainingTypes() {
349
+ return this.httpClient.request('/training-types');
350
+ }
351
+ async getGoalMetrics() {
352
+ return this.httpClient.request('/goal-metrics');
353
+ }
354
+ /**
355
+ * Register or update a personal device for the user.
356
+ *
357
+ * NOTE: This endpoint has side effects and should be used with caution.
358
+ * It registers the device with Tonal's system and may affect notification
359
+ * settings and device management. For reverse-engineered clients, this
360
+ * could be considered unauthorized device registration.
361
+ *
362
+ * @internal This method is primarily for API completeness and documentation
363
+ */
364
+ async registerPersonalDevice(userId, deviceInfo) {
365
+ return this.httpClient.request(`/users/${userId}/personal-devices`, {
366
+ method: 'POST',
367
+ body: JSON.stringify(deviceInfo),
368
+ });
369
+ }
370
+ /**
371
+ * Get user privacy permissions/settings.
372
+ *
373
+ * Returns what information this user has made public vs private.
374
+ * Useful for understanding social features and respecting privacy preferences.
375
+ *
376
+ * @internal This method is for understanding user privacy settings
377
+ */
378
+ async getUserPermissions(userId) {
379
+ return this.httpClient.request(`/users/${userId}/permissions`);
380
+ }
381
+ /**
382
+ * Get comprehensive user settings and preferences.
383
+ *
384
+ * Returns audio/visual settings, feature flags, onboarding states, and user preferences.
385
+ * Provides insight into Tonal's full feature ecosystem and user customization options.
386
+ *
387
+ * @internal This method is for understanding user preferences and feature usage
388
+ */
389
+ async getUserSettings(userId) {
390
+ return this.httpClient.request(`/users/${userId}/user-settings`);
391
+ }
392
+ async getDailyMetrics(userId, days = 60) {
393
+ return this.httpClient.request(`/users/${userId}/metrics/daily?days=${days}`);
394
+ }
395
+ async getCurrentStreak(userId) {
396
+ return this.httpClient.request(`/users/${userId}/streaks/current`);
397
+ }
398
+ async getActivitySummaries(userId) {
399
+ return this.httpClient.request(`/users/${userId}/activity-summaries`);
400
+ }
401
+ async getUserStatistics(userId) {
402
+ return this.httpClient.request(`/users/${userId}/statistics`);
403
+ }
404
+ async getAchievementStats(userId) {
405
+ return this.httpClient.request(`/users/${userId}/achievement-stats`);
406
+ }
407
+ async getAchievements(userId) {
408
+ return this.httpClient.request(`/users/${userId}/achievements`);
409
+ }
410
+ async getHomeCalendar(userId) {
411
+ return this.httpClient.request(`/users/${userId}/calendar/home`);
412
+ }
413
+ async getMuscleReadiness(userId) {
414
+ return this.httpClient.request(`/users/${userId}/muscle-readiness/current`);
415
+ }
416
+ async getProgramById(programId) {
417
+ return this.httpClient.request(`/programs/${programId}`);
418
+ }
419
+ async getTargetScores(userId) {
420
+ return this.httpClient.request(`/users/${userId}/target-scores`);
421
+ }
422
+ async getMetricScores(userId, startWeek) {
423
+ const url = startWeek
424
+ ? `/users/${userId}/metric-scores?startWeek=${startWeek}`
425
+ : `/users/${userId}/metric-scores`;
426
+ return this.httpClient.request(url);
427
+ }
428
+ }
429
+
430
+ class TonalClient {
431
+ constructor(username, password) {
432
+ this.authManager = new AuthManager(username, password);
433
+ this.httpClient = new HttpClient(this.authManager);
434
+ this.workoutService = new WorkoutService(this.httpClient);
435
+ this.movementService = new MovementService(this.httpClient);
436
+ this.userService = new UserService(this.httpClient);
437
+ }
438
+ static async create(credentials) {
439
+ const client = new TonalClient(credentials.username, credentials.password);
440
+ await client.authManager.authenticate();
441
+ return client;
442
+ }
443
+ // Movement operations
444
+ async getMovements() {
445
+ return this.movementService.getMovements();
446
+ }
447
+ // User operations
448
+ async getUserInfo() {
449
+ return this.userService.getUserInfo();
450
+ }
451
+ async getGoals() {
452
+ return this.userService.getGoals();
453
+ }
454
+ async getTrainingEffectGoals() {
455
+ return this.userService.getTrainingEffectGoals();
456
+ }
457
+ async getTrainingTypes() {
458
+ return this.userService.getTrainingTypes();
459
+ }
460
+ async getGoalMetrics() {
461
+ return this.userService.getGoalMetrics();
462
+ }
463
+ async getUserSettings() {
464
+ const userInfo = await this.getUserInfo();
465
+ return this.userService.getUserSettings(userInfo.id);
466
+ }
467
+ async getDailyMetrics(days = 60) {
468
+ const userInfo = await this.getUserInfo();
469
+ return this.userService.getDailyMetrics(userInfo.id, days);
470
+ }
471
+ async getCurrentStreak() {
472
+ const userInfo = await this.getUserInfo();
473
+ return this.userService.getCurrentStreak(userInfo.id);
474
+ }
475
+ async getActivitySummaries() {
476
+ const userInfo = await this.getUserInfo();
477
+ return this.userService.getActivitySummaries(userInfo.id);
478
+ }
479
+ async getUserStatistics() {
480
+ const userInfo = await this.getUserInfo();
481
+ return this.userService.getUserStatistics(userInfo.id);
482
+ }
483
+ async getAchievementStats() {
484
+ const userInfo = await this.getUserInfo();
485
+ return this.userService.getAchievementStats(userInfo.id);
486
+ }
487
+ async getAchievements() {
488
+ const userInfo = await this.getUserInfo();
489
+ return this.userService.getAchievements(userInfo.id);
490
+ }
491
+ async getHomeCalendar() {
492
+ const userInfo = await this.getUserInfo();
493
+ return this.userService.getHomeCalendar(userInfo.id);
494
+ }
495
+ async getMuscleReadiness() {
496
+ const userInfo = await this.getUserInfo();
497
+ return this.userService.getMuscleReadiness(userInfo.id);
498
+ }
499
+ async getProgramById(programId) {
500
+ return this.userService.getProgramById(programId);
501
+ }
502
+ async getTargetScores() {
503
+ const userInfo = await this.getUserInfo();
504
+ return this.userService.getTargetScores(userInfo.id);
505
+ }
506
+ async getMetricScores(startWeek) {
507
+ const userInfo = await this.getUserInfo();
508
+ return this.userService.getMetricScores(userInfo.id, startWeek);
509
+ }
510
+ // Workout operations
511
+ async getUserWorkouts(offset = 0, limit = 50) {
512
+ return this.workoutService.getUserWorkouts(offset, limit);
513
+ }
514
+ async getDailyLifts(timeZone) {
515
+ // Get user info to populate device-specific headers
516
+ const userInfo = await this.getUserInfo();
517
+ return this.workoutService.getDailyLifts(userInfo, timeZone);
518
+ }
519
+ async getWorkoutById(workoutId) {
520
+ return this.workoutService.getWorkoutById(workoutId);
521
+ }
522
+ async getWorkoutByShareUrl(shareUrl) {
523
+ return this.workoutService.getWorkoutByShareUrl(shareUrl);
524
+ }
525
+ async estimateWorkoutDuration(sets) {
526
+ return this.workoutService.estimateWorkoutDuration(sets);
527
+ }
528
+ async createWorkout(workoutData) {
529
+ return this.workoutService.createWorkout(workoutData);
530
+ }
531
+ async updateWorkout(workoutData) {
532
+ return this.workoutService.updateWorkout(workoutData);
533
+ }
534
+ async deleteWorkout(workoutId) {
535
+ return this.workoutService.deleteWorkout(workoutId);
536
+ }
145
537
  }
146
538
 
147
- export { TonalClient as default };
539
+ export { TonalClient, TonalClientError, TonalClient as default };