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