@nativesquare/soma 0.10.0 → 0.10.2

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 (31) hide show
  1. package/dist/client/index.d.ts +85 -163
  2. package/dist/client/index.d.ts.map +1 -1
  3. package/dist/client/index.js +109 -130
  4. package/dist/client/index.js.map +1 -1
  5. package/dist/component/_generated/component.d.ts +92 -35
  6. package/dist/component/_generated/component.d.ts.map +1 -1
  7. package/dist/component/garmin/private.d.ts +9 -0
  8. package/dist/component/garmin/private.d.ts.map +1 -1
  9. package/dist/component/garmin/private.js +49 -0
  10. package/dist/component/garmin/private.js.map +1 -1
  11. package/dist/component/garmin/public.d.ts +237 -62
  12. package/dist/component/garmin/public.d.ts.map +1 -1
  13. package/dist/component/garmin/public.js +683 -253
  14. package/dist/component/garmin/public.js.map +1 -1
  15. package/dist/component/garmin/utils.d.ts +8 -0
  16. package/dist/component/garmin/utils.d.ts.map +1 -1
  17. package/dist/component/garmin/utils.js +9 -0
  18. package/dist/component/garmin/utils.js.map +1 -1
  19. package/dist/component/strava/public.d.ts +12 -52
  20. package/dist/component/strava/public.d.ts.map +1 -1
  21. package/dist/component/strava/public.js +16 -92
  22. package/dist/component/strava/public.js.map +1 -1
  23. package/dist/component/strava/transform/activity.js +15 -9
  24. package/dist/component/strava/transform/activity.js.map +1 -1
  25. package/package.json +1 -1
  26. package/src/client/index.ts +210 -158
  27. package/src/component/_generated/component.ts +165 -31
  28. package/src/component/garmin/private.ts +84 -0
  29. package/src/component/garmin/public.ts +804 -347
  30. package/src/component/garmin/utils.ts +17 -0
  31. package/src/component/strava/public.ts +17 -123
@@ -7,7 +7,7 @@ import { action } from "../_generated/server";
7
7
  import { generateState } from "../utils.js";
8
8
  import { generateCodeVerifier, generateCodeChallenge, buildAuthUrl, exchangeCode, refreshToken, } from "./auth.js";
9
9
  import { createWellnessClient, createTrainingClient, } from "./client.js";
10
- import { timeRangeQuery } from "./utils.js";
10
+ import { buildTimeRangeQuery, timeRangeQuery } from "./utils.js";
11
11
  import { createWorkoutV2 as sdkCreateWorkoutV2, createWorkoutSchedule as sdkCreateWorkoutSchedule, } from "./types/trainingApiWorkouts/sdk.gen";
12
12
  import { userId as sdkUserId, dereg as sdkDereg, getActivities, getDailies, getSleeps, getBodyComps, getMct, getBloodPressures, getSkinTemp, getUserMetrics, getHrv, getStressDetails, getPulseox, getRespiration, } from "./types/wellnessApi/sdk.gen";
13
13
  import { transformActivity } from "./transform/activity.js";
@@ -28,23 +28,19 @@ import { api, internal } from "../_generated/api";
28
28
  const DEFAULT_SYNC_DAYS = 30;
29
29
  // Refresh buffer: refresh tokens 10 minutes before expiry
30
30
  const REFRESH_BUFFER_SECONDS = 600;
31
- // ─── Public Actions ──────────────────────────────────────────────────────────
31
+ // ─── OAuth ──────────────────────────────────────────────────────────────────
32
32
  /**
33
33
  * Generate a Garmin OAuth 2.0 authorization URL with PKCE.
34
34
  *
35
- * If `userId` is provided, the PKCE code verifier and state are stored in the
36
- * component's `pendingOAuth` table so that `completeGarminOAuth` can look
37
- * them up automatically when the callback fires. This is the recommended
38
- * flow when using `registerRoutes`.
39
- *
40
- * If `userId` is omitted, the host app must store the returned `codeVerifier`
41
- * itself and pass it to `connectGarmin` manually.
35
+ * The PKCE code verifier and state are stored in the component's
36
+ * `pendingOAuth` table so that `completeGarminOAuth` can look them up
37
+ * automatically when the callback fires via `registerRoutes`.
42
38
  */
43
39
  export const getGarminAuthUrl = action({
44
40
  args: {
45
41
  clientId: v.string(),
46
42
  redirectUri: v.optional(v.string()),
47
- userId: v.optional(v.string()),
43
+ userId: v.string(),
48
44
  },
49
45
  handler: async (ctx, args) => {
50
46
  const codeVerifier = generateCodeVerifier();
@@ -56,94 +52,25 @@ export const getGarminAuthUrl = action({
56
52
  redirectUri: args.redirectUri,
57
53
  state,
58
54
  });
59
- if (args.userId) {
60
- await ctx.runMutation(internal.garmin.private.storePendingOAuth, {
61
- provider: "GARMIN",
62
- state,
63
- codeVerifier,
64
- userId: args.userId,
65
- });
66
- }
67
- return { authUrl, state, codeVerifier };
68
- },
69
- });
70
- /**
71
- * Exchange an authorization code for tokens + initial sync.
72
- *
73
- * Used in the manual flow where the host app stores the code verifier
74
- * and handles the callback itself.
75
- */
76
- export const connectGarmin = action({
77
- args: {
78
- userId: v.string(),
79
- clientId: v.string(),
80
- clientSecret: v.string(),
81
- code: v.string(),
82
- codeVerifier: v.string(),
83
- redirectUri: v.optional(v.string()),
84
- },
85
- handler: async (ctx, args) => {
86
- const tokenResult = await exchangeCode({
87
- clientId: args.clientId,
88
- clientSecret: args.clientSecret,
89
- code: args.code,
90
- codeVerifier: args.codeVerifier,
91
- redirectUri: args.redirectUri,
92
- });
93
- const connectionId = await ctx.runMutation(api.public.connect, {
94
- userId: args.userId,
55
+ await ctx.runMutation(internal.garmin.private.storePendingOAuth, {
95
56
  provider: "GARMIN",
96
- });
97
- const expiresAt = Math.floor(Date.now() / 1000) + tokenResult.expires_in;
98
- const _stored = await ctx.runMutation(internal.garmin.private.storeTokens, {
99
- connectionId,
100
- accessToken: tokenResult.access_token,
101
- refreshToken: tokenResult.refresh_token,
102
- expiresAt,
103
- });
104
- // Best-effort: resolve Garmin user ID for webhook mapping
105
- const wellnessClient = createWellnessClient(tokenResult.access_token);
106
- const { data: userIdData } = await sdkUserId({ client: wellnessClient });
107
- const garminUserId = userIdData?.userId ?? null;
108
- if (garminUserId) {
109
- const _updated = await ctx.runMutation(api.public.updateConnection, {
110
- connectionId,
111
- providerUserId: garminUserId,
112
- });
113
- }
114
- const now = Math.floor(Date.now() / 1000);
115
- const thirtyDaysAgo = now - DEFAULT_SYNC_DAYS * 86400;
116
- const timeRange = {
117
- uploadStartTimeInSeconds: thirtyDaysAgo,
118
- uploadEndTimeInSeconds: now,
119
- };
120
- const result = await ctx.runAction(api.garmin.public.syncAllTypes, {
121
- accessToken: tokenResult.access_token,
122
- connectionId,
57
+ state,
58
+ codeVerifier,
123
59
  userId: args.userId,
124
- uploadStartTimeInSeconds: timeRange.uploadStartTimeInSeconds,
125
- uploadEndTimeInSeconds: timeRange.uploadEndTimeInSeconds,
126
60
  });
127
- const _updated = await ctx.runMutation(api.public.updateConnection, {
128
- connectionId,
129
- lastDataUpdate: new Date().toISOString(),
130
- });
131
- return {
132
- connectionId,
133
- userId: args.userId,
134
- synced: result.synced,
135
- errors: result.errors,
136
- };
61
+ return { authUrl, state, codeVerifier };
137
62
  },
138
63
  });
139
64
  /**
140
65
  * Complete a Garmin OAuth 2.0 flow using stored pending state.
141
66
  *
142
- * Used by `registerRoutes` — the callback handler calls this with the
143
- * `code` and `state` from the redirect. The action looks up the pending
144
- * state (codeVerifier, userId) stored during `getGarminAuthUrl`,
145
- * exchanges for tokens, creates the connection, syncs data, and
146
- * cleans up the pending entry.
67
+ * Called internally by `registerRoutes` — the callback handler calls
68
+ * this with the `code` and `state` from the redirect. The action looks
69
+ * up the pending state (codeVerifier, userId) stored during
70
+ * `getGarminAuthUrl`, exchanges for tokens, creates the connection,
71
+ * stores tokens, and cleans up the pending entry.
72
+ *
73
+ * The host app is responsible for calling `syncGarmin` afterwards.
147
74
  */
148
75
  export const completeGarminOAuth = action({
149
76
  args: {
@@ -196,29 +123,570 @@ export const completeGarminOAuth = action({
196
123
  providerUserId: garminUserId,
197
124
  });
198
125
  }
199
- const now = Math.floor(Date.now() / 1000);
200
- const thirtyDaysAgo = now - DEFAULT_SYNC_DAYS * 86400;
201
- const timeRange = {
202
- uploadStartTimeInSeconds: thirtyDaysAgo,
203
- uploadEndTimeInSeconds: now,
204
- };
205
- const result = await ctx.runAction(api.garmin.public.syncAllTypes, {
206
- accessToken: tokenResult.access_token,
126
+ return {
207
127
  connectionId,
208
128
  userId: pending.userId,
209
- uploadStartTimeInSeconds: timeRange.uploadStartTimeInSeconds,
210
- uploadEndTimeInSeconds: timeRange.uploadEndTimeInSeconds,
129
+ };
130
+ },
131
+ });
132
+ /**
133
+ * Disconnect a user from Garmin.
134
+ *
135
+ * Deregisters the user via the Garmin API (best-effort), deletes stored
136
+ * tokens, and sets the connection to inactive.
137
+ */
138
+ export const disconnectGarmin = action({
139
+ args: {
140
+ userId: v.string(),
141
+ },
142
+ handler: async (ctx, args) => {
143
+ const connection = await ctx.runQuery(internal.private.getConnectionByProvider, { userId: args.userId, provider: "GARMIN" });
144
+ if (!connection) {
145
+ throw new Error(`No Garmin connection found for user "${args.userId}".`);
146
+ }
147
+ const connectionId = connection._id;
148
+ // Best-effort: deregister user at Garmin
149
+ const tokenDoc = await ctx.runQuery(internal.garmin.private.getTokens, {
150
+ connectionId,
211
151
  });
212
- const _updated = await ctx.runMutation(api.public.updateConnection, {
152
+ if (tokenDoc) {
153
+ try {
154
+ const wellnessClient = createWellnessClient(tokenDoc.accessToken);
155
+ await sdkDereg({ client: wellnessClient });
156
+ }
157
+ catch {
158
+ // Deregistration is best-effort; proceed with local cleanup
159
+ }
160
+ }
161
+ const _deleted = await ctx.runMutation(internal.garmin.private.deleteTokens, { connectionId });
162
+ const _disconnected = await ctx.runMutation(api.public.disconnect, {
163
+ userId: args.userId,
164
+ provider: "GARMIN",
165
+ });
166
+ return null;
167
+ },
168
+ });
169
+ // ─── Pull ───────────────────────────────────────────────────────────────────
170
+ export const pullActivities = action({
171
+ args: {
172
+ userId: v.string(),
173
+ clientId: v.string(),
174
+ clientSecret: v.string(),
175
+ startTimeInSeconds: v.optional(v.number()),
176
+ endTimeInSeconds: v.optional(v.number()),
177
+ },
178
+ handler: async (ctx, args) => {
179
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, {
180
+ userId: args.userId,
181
+ clientId: args.clientId,
182
+ clientSecret: args.clientSecret,
183
+ });
184
+ const timeRangeQuery = buildTimeRangeQuery(args, accessToken);
185
+ const wellnessClient = createWellnessClient(accessToken);
186
+ const synced = { activities: 0 };
187
+ const errors = [];
188
+ try {
189
+ const { data: activities, error } = await getActivities({
190
+ client: wellnessClient,
191
+ query: timeRangeQuery,
192
+ });
193
+ if (error || !activities) {
194
+ throw new Error(error ? JSON.stringify(error) : "No data");
195
+ }
196
+ for (const activity of activities) {
197
+ try {
198
+ const data = transformActivity(activity);
199
+ await ctx.runMutation(api.public.ingestActivity, {
200
+ connectionId,
201
+ userId: args.userId,
202
+ ...data,
203
+ });
204
+ synced.activities++;
205
+ }
206
+ catch (err) {
207
+ errors.push({
208
+ type: "activity",
209
+ id: activity.summaryId ?? String(activity.activityId),
210
+ error: err instanceof Error ? err.message : String(err),
211
+ });
212
+ }
213
+ }
214
+ }
215
+ catch (err) {
216
+ errors.push({
217
+ type: "activity",
218
+ id: "fetch",
219
+ error: err instanceof Error ? err.message : String(err),
220
+ });
221
+ }
222
+ await ctx.runMutation(api.public.updateConnection, {
213
223
  connectionId,
214
224
  lastDataUpdate: new Date().toISOString(),
215
225
  });
216
- return {
217
- connectionId,
218
- userId: pending.userId,
219
- synced: result.synced,
220
- errors: result.errors,
226
+ return { synced, errors };
227
+ },
228
+ });
229
+ export const pullDailies = action({
230
+ args: {
231
+ userId: v.string(),
232
+ clientId: v.string(),
233
+ clientSecret: v.string(),
234
+ startTimeInSeconds: v.optional(v.number()),
235
+ endTimeInSeconds: v.optional(v.number()),
236
+ },
237
+ handler: async (ctx, args) => {
238
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
239
+ const query = buildTimeRangeQuery(args, accessToken);
240
+ const wellnessClient = createWellnessClient(accessToken);
241
+ const synced = { dailies: 0 };
242
+ const errors = [];
243
+ try {
244
+ const { data: dailies, error } = await getDailies({ client: wellnessClient, query });
245
+ if (error || !dailies)
246
+ throw new Error(error ? JSON.stringify(error) : "No data");
247
+ for (const daily of dailies) {
248
+ try {
249
+ const data = transformDailies(daily);
250
+ if (!data)
251
+ continue;
252
+ await ctx.runMutation(api.public.ingestDaily, { connectionId, userId: args.userId, ...data });
253
+ synced.dailies++;
254
+ }
255
+ catch (err) {
256
+ errors.push({ type: "daily", id: daily.summaryId ?? daily.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
257
+ }
258
+ }
259
+ }
260
+ catch (err) {
261
+ errors.push({ type: "daily", id: "fetch", error: err instanceof Error ? err.message : String(err) });
262
+ }
263
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
264
+ return { synced, errors };
265
+ },
266
+ });
267
+ export const pullSleep = action({
268
+ args: {
269
+ userId: v.string(),
270
+ clientId: v.string(),
271
+ clientSecret: v.string(),
272
+ startTimeInSeconds: v.optional(v.number()),
273
+ endTimeInSeconds: v.optional(v.number()),
274
+ },
275
+ handler: async (ctx, args) => {
276
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
277
+ const query = buildTimeRangeQuery(args, accessToken);
278
+ const wellnessClient = createWellnessClient(accessToken);
279
+ const synced = { sleep: 0 };
280
+ const errors = [];
281
+ try {
282
+ const { data: sleeps, error } = await getSleeps({ client: wellnessClient, query });
283
+ if (error || !sleeps)
284
+ throw new Error(error ? JSON.stringify(error) : "No data");
285
+ for (const sleep of sleeps) {
286
+ try {
287
+ const data = transformSleeps(sleep);
288
+ await ctx.runMutation(api.public.ingestSleep, { connectionId, userId: args.userId, ...data });
289
+ synced.sleep++;
290
+ }
291
+ catch (err) {
292
+ errors.push({ type: "sleep", id: sleep.summaryId ?? sleep.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
293
+ }
294
+ }
295
+ }
296
+ catch (err) {
297
+ errors.push({ type: "sleep", id: "fetch", error: err instanceof Error ? err.message : String(err) });
298
+ }
299
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
300
+ return { synced, errors };
301
+ },
302
+ });
303
+ export const pullBody = action({
304
+ args: {
305
+ userId: v.string(),
306
+ clientId: v.string(),
307
+ clientSecret: v.string(),
308
+ startTimeInSeconds: v.optional(v.number()),
309
+ endTimeInSeconds: v.optional(v.number()),
310
+ },
311
+ handler: async (ctx, args) => {
312
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
313
+ const query = buildTimeRangeQuery(args, accessToken);
314
+ const wellnessClient = createWellnessClient(accessToken);
315
+ const synced = { body: 0 };
316
+ const errors = [];
317
+ try {
318
+ const { data: bodyComps, error } = await getBodyComps({ client: wellnessClient, query });
319
+ if (error || !bodyComps)
320
+ throw new Error(error ? JSON.stringify(error) : "No data");
321
+ for (const body of bodyComps) {
322
+ try {
323
+ const data = transformBodyComposition(body);
324
+ if (!data)
325
+ continue;
326
+ await ctx.runMutation(api.public.ingestBody, { connectionId, userId: args.userId, ...data });
327
+ synced.body++;
328
+ }
329
+ catch (err) {
330
+ errors.push({ type: "body", id: body.summaryId ?? String(body.measurementTimeInSeconds), error: err instanceof Error ? err.message : String(err) });
331
+ }
332
+ }
333
+ }
334
+ catch (err) {
335
+ errors.push({ type: "body", id: "fetch", error: err instanceof Error ? err.message : String(err) });
336
+ }
337
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
338
+ return { synced, errors };
339
+ },
340
+ });
341
+ export const pullMenstruation = action({
342
+ args: {
343
+ userId: v.string(),
344
+ clientId: v.string(),
345
+ clientSecret: v.string(),
346
+ startTimeInSeconds: v.optional(v.number()),
347
+ endTimeInSeconds: v.optional(v.number()),
348
+ },
349
+ handler: async (ctx, args) => {
350
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
351
+ const query = buildTimeRangeQuery(args, accessToken);
352
+ const wellnessClient = createWellnessClient(accessToken);
353
+ const synced = { menstruation: 0 };
354
+ const errors = [];
355
+ try {
356
+ const { data: records, error } = await getMct({ client: wellnessClient, query });
357
+ if (error || !records)
358
+ throw new Error(error ? JSON.stringify(error) : "No data");
359
+ for (const record of records) {
360
+ try {
361
+ const data = transformMenstrualCycleTracking(record);
362
+ await ctx.runMutation(api.public.ingestMenstruation, { connectionId, userId: args.userId, ...data });
363
+ synced.menstruation++;
364
+ }
365
+ catch (err) {
366
+ errors.push({ type: "menstruation", id: record.summaryId ?? record.periodStartDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
367
+ }
368
+ }
369
+ }
370
+ catch (err) {
371
+ errors.push({ type: "menstruation", id: "fetch", error: err instanceof Error ? err.message : String(err) });
372
+ }
373
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
374
+ return { synced, errors };
375
+ },
376
+ });
377
+ export const pullBloodPressures = action({
378
+ args: {
379
+ userId: v.string(),
380
+ clientId: v.string(),
381
+ clientSecret: v.string(),
382
+ startTimeInSeconds: v.optional(v.number()),
383
+ endTimeInSeconds: v.optional(v.number()),
384
+ },
385
+ handler: async (ctx, args) => {
386
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
387
+ const query = buildTimeRangeQuery(args, accessToken);
388
+ const wellnessClient = createWellnessClient(accessToken);
389
+ const synced = { bloodPressures: 0 };
390
+ const errors = [];
391
+ try {
392
+ const { data: bpRecords, error } = await getBloodPressures({ client: wellnessClient, query });
393
+ if (error || !bpRecords)
394
+ throw new Error(error ? JSON.stringify(error) : "No data");
395
+ for (const bp of bpRecords) {
396
+ try {
397
+ const data = transformBloodPressure(bp);
398
+ if (!data)
399
+ continue;
400
+ await ctx.runMutation(api.public.ingestBody, { connectionId, userId: args.userId, ...data });
401
+ synced.bloodPressures++;
402
+ }
403
+ catch (err) {
404
+ errors.push({ type: "bloodPressure", id: bp.summaryId ?? String(bp.measurementTimeInSeconds), error: err instanceof Error ? err.message : String(err) });
405
+ }
406
+ }
407
+ }
408
+ catch (err) {
409
+ errors.push({ type: "bloodPressure", id: "fetch", error: err instanceof Error ? err.message : String(err) });
410
+ }
411
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
412
+ return { synced, errors };
413
+ },
414
+ });
415
+ export const pullSkinTemperature = action({
416
+ args: {
417
+ userId: v.string(),
418
+ clientId: v.string(),
419
+ clientSecret: v.string(),
420
+ startTimeInSeconds: v.optional(v.number()),
421
+ endTimeInSeconds: v.optional(v.number()),
422
+ },
423
+ handler: async (ctx, args) => {
424
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
425
+ const query = buildTimeRangeQuery(args, accessToken);
426
+ const wellnessClient = createWellnessClient(accessToken);
427
+ const synced = { skinTemp: 0 };
428
+ const errors = [];
429
+ try {
430
+ const { data: skinRecords, error } = await getSkinTemp({ client: wellnessClient, query });
431
+ if (error || !skinRecords)
432
+ throw new Error(error ? JSON.stringify(error) : "No data");
433
+ for (const skin of skinRecords) {
434
+ try {
435
+ const data = transformSkinTemperature(skin);
436
+ if (!data)
437
+ continue;
438
+ await ctx.runMutation(api.public.ingestBody, { connectionId, userId: args.userId, ...data });
439
+ synced.skinTemp++;
440
+ }
441
+ catch (err) {
442
+ errors.push({ type: "skinTemp", id: skin.summaryId ?? skin.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
443
+ }
444
+ }
445
+ }
446
+ catch (err) {
447
+ errors.push({ type: "skinTemp", id: "fetch", error: err instanceof Error ? err.message : String(err) });
448
+ }
449
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
450
+ return { synced, errors };
451
+ },
452
+ });
453
+ export const pullUserMetrics = action({
454
+ args: {
455
+ userId: v.string(),
456
+ clientId: v.string(),
457
+ clientSecret: v.string(),
458
+ startTimeInSeconds: v.optional(v.number()),
459
+ endTimeInSeconds: v.optional(v.number()),
460
+ },
461
+ handler: async (ctx, args) => {
462
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
463
+ const query = buildTimeRangeQuery(args, accessToken);
464
+ const wellnessClient = createWellnessClient(accessToken);
465
+ const synced = { userMetrics: 0 };
466
+ const errors = [];
467
+ try {
468
+ const { data: metricsRecords, error } = await getUserMetrics({ client: wellnessClient, query });
469
+ if (error || !metricsRecords)
470
+ throw new Error(error ? JSON.stringify(error) : "No data");
471
+ for (const metrics of metricsRecords) {
472
+ try {
473
+ const data = transformUserMetrics(metrics);
474
+ if (!data)
475
+ continue;
476
+ await ctx.runMutation(api.public.ingestBody, { connectionId, userId: args.userId, ...data });
477
+ synced.userMetrics++;
478
+ }
479
+ catch (err) {
480
+ errors.push({ type: "userMetrics", id: metrics.summaryId ?? metrics.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
481
+ }
482
+ }
483
+ }
484
+ catch (err) {
485
+ errors.push({ type: "userMetrics", id: "fetch", error: err instanceof Error ? err.message : String(err) });
486
+ }
487
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
488
+ return { synced, errors };
489
+ },
490
+ });
491
+ export const pullHRV = action({
492
+ args: {
493
+ userId: v.string(),
494
+ clientId: v.string(),
495
+ clientSecret: v.string(),
496
+ startTimeInSeconds: v.optional(v.number()),
497
+ endTimeInSeconds: v.optional(v.number()),
498
+ },
499
+ handler: async (ctx, args) => {
500
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
501
+ const query = buildTimeRangeQuery(args, accessToken);
502
+ const wellnessClient = createWellnessClient(accessToken);
503
+ const synced = { hrv: 0 };
504
+ const errors = [];
505
+ try {
506
+ const { data: hrvRecords, error } = await getHrv({ client: wellnessClient, query });
507
+ if (error || !hrvRecords)
508
+ throw new Error(error ? JSON.stringify(error) : "No data");
509
+ for (const hrv of hrvRecords) {
510
+ try {
511
+ const data = transformHRVSummary(hrv);
512
+ if (!data)
513
+ continue;
514
+ await ctx.runMutation(api.public.ingestDaily, { connectionId, userId: args.userId, ...data });
515
+ synced.hrv++;
516
+ }
517
+ catch (err) {
518
+ errors.push({ type: "hrv", id: hrv.summaryId ?? hrv.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
519
+ }
520
+ }
521
+ }
522
+ catch (err) {
523
+ errors.push({ type: "hrv", id: "fetch", error: err instanceof Error ? err.message : String(err) });
524
+ }
525
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
526
+ return { synced, errors };
527
+ },
528
+ });
529
+ export const pullStressDetails = action({
530
+ args: {
531
+ userId: v.string(),
532
+ clientId: v.string(),
533
+ clientSecret: v.string(),
534
+ startTimeInSeconds: v.optional(v.number()),
535
+ endTimeInSeconds: v.optional(v.number()),
536
+ },
537
+ handler: async (ctx, args) => {
538
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
539
+ const query = buildTimeRangeQuery(args, accessToken);
540
+ const wellnessClient = createWellnessClient(accessToken);
541
+ const synced = { stressDetails: 0 };
542
+ const errors = [];
543
+ try {
544
+ const { data: stressRecords, error } = await getStressDetails({ client: wellnessClient, query });
545
+ if (error || !stressRecords)
546
+ throw new Error(error ? JSON.stringify(error) : "No data");
547
+ for (const stress of stressRecords) {
548
+ try {
549
+ const data = transformStress(stress);
550
+ if (!data)
551
+ continue;
552
+ await ctx.runMutation(api.public.ingestDaily, { connectionId, userId: args.userId, ...data });
553
+ synced.stressDetails++;
554
+ }
555
+ catch (err) {
556
+ errors.push({ type: "stressDetails", id: stress.summaryId ?? stress.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
557
+ }
558
+ }
559
+ }
560
+ catch (err) {
561
+ errors.push({ type: "stressDetails", id: "fetch", error: err instanceof Error ? err.message : String(err) });
562
+ }
563
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
564
+ return { synced, errors };
565
+ },
566
+ });
567
+ export const pullPulseOx = action({
568
+ args: {
569
+ userId: v.string(),
570
+ clientId: v.string(),
571
+ clientSecret: v.string(),
572
+ startTimeInSeconds: v.optional(v.number()),
573
+ endTimeInSeconds: v.optional(v.number()),
574
+ },
575
+ handler: async (ctx, args) => {
576
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
577
+ const query = buildTimeRangeQuery(args, accessToken);
578
+ const wellnessClient = createWellnessClient(accessToken);
579
+ const synced = { pulseOx: 0 };
580
+ const errors = [];
581
+ try {
582
+ const { data: pulseOxRecords, error } = await getPulseox({ client: wellnessClient, query });
583
+ if (error || !pulseOxRecords)
584
+ throw new Error(error ? JSON.stringify(error) : "No data");
585
+ for (const po of pulseOxRecords) {
586
+ try {
587
+ const data = transformPulseOx(po);
588
+ if (!data)
589
+ continue;
590
+ await ctx.runMutation(api.public.ingestDaily, { connectionId, userId: args.userId, ...data });
591
+ synced.pulseOx++;
592
+ }
593
+ catch (err) {
594
+ errors.push({ type: "pulseOx", id: po.summaryId ?? po.calendarDate ?? "unknown", error: err instanceof Error ? err.message : String(err) });
595
+ }
596
+ }
597
+ }
598
+ catch (err) {
599
+ errors.push({ type: "pulseOx", id: "fetch", error: err instanceof Error ? err.message : String(err) });
600
+ }
601
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
602
+ return { synced, errors };
603
+ },
604
+ });
605
+ export const pullRespiration = action({
606
+ args: {
607
+ userId: v.string(),
608
+ clientId: v.string(),
609
+ clientSecret: v.string(),
610
+ startTimeInSeconds: v.optional(v.number()),
611
+ endTimeInSeconds: v.optional(v.number()),
612
+ },
613
+ handler: async (ctx, args) => {
614
+ const { connectionId, accessToken } = await ctx.runAction(internal.garmin.private.resolveConnectionAndAccessToken, { userId: args.userId, clientId: args.clientId, clientSecret: args.clientSecret });
615
+ const query = buildTimeRangeQuery(args, accessToken);
616
+ const wellnessClient = createWellnessClient(accessToken);
617
+ const synced = { respiration: 0 };
618
+ const errors = [];
619
+ try {
620
+ const { data: respRecords, error } = await getRespiration({ client: wellnessClient, query });
621
+ if (error || !respRecords)
622
+ throw new Error(error ? JSON.stringify(error) : "No data");
623
+ for (const resp of respRecords) {
624
+ try {
625
+ const data = transformRespiration(resp);
626
+ if (!data)
627
+ continue;
628
+ await ctx.runMutation(api.public.ingestDaily, { connectionId, userId: args.userId, ...data });
629
+ synced.respiration++;
630
+ }
631
+ catch (err) {
632
+ errors.push({ type: "respiration", id: resp.summaryId ?? "unknown", error: err instanceof Error ? err.message : String(err) });
633
+ }
634
+ }
635
+ }
636
+ catch (err) {
637
+ errors.push({ type: "respiration", id: "fetch", error: err instanceof Error ? err.message : String(err) });
638
+ }
639
+ await ctx.runMutation(api.public.updateConnection, { connectionId, lastDataUpdate: new Date().toISOString() });
640
+ return { synced, errors };
641
+ },
642
+ });
643
+ export const pullAll = action({
644
+ args: {
645
+ userId: v.string(),
646
+ clientId: v.string(),
647
+ clientSecret: v.string(),
648
+ startTimeInSeconds: v.optional(v.number()),
649
+ endTimeInSeconds: v.optional(v.number()),
650
+ },
651
+ handler: async (ctx, args) => {
652
+ const sharedArgs = {
653
+ userId: args.userId,
654
+ clientId: args.clientId,
655
+ clientSecret: args.clientSecret,
656
+ startTimeInSeconds: args.startTimeInSeconds,
657
+ endTimeInSeconds: args.endTimeInSeconds,
221
658
  };
659
+ const pullFns = [
660
+ { ref: api.garmin.public.pullActivities, name: "activities" },
661
+ { ref: api.garmin.public.pullDailies, name: "dailies" },
662
+ { ref: api.garmin.public.pullSleep, name: "sleep" },
663
+ { ref: api.garmin.public.pullBody, name: "body" },
664
+ { ref: api.garmin.public.pullMenstruation, name: "menstruation" },
665
+ { ref: api.garmin.public.pullBloodPressures, name: "bloodPressures" },
666
+ { ref: api.garmin.public.pullSkinTemperature, name: "skinTemp" },
667
+ { ref: api.garmin.public.pullUserMetrics, name: "userMetrics" },
668
+ { ref: api.garmin.public.pullHRV, name: "hrv" },
669
+ { ref: api.garmin.public.pullStressDetails, name: "stressDetails" },
670
+ { ref: api.garmin.public.pullPulseOx, name: "pulseOx" },
671
+ { ref: api.garmin.public.pullRespiration, name: "respiration" },
672
+ ];
673
+ const synced = {};
674
+ const errors = [];
675
+ for (const { ref, name } of pullFns) {
676
+ try {
677
+ const result = await ctx.runAction(ref, sharedArgs);
678
+ Object.assign(synced, result.synced);
679
+ errors.push(...result.errors);
680
+ }
681
+ catch (err) {
682
+ errors.push({
683
+ type: name,
684
+ id: "pull",
685
+ error: err instanceof Error ? err.message : String(err),
686
+ });
687
+ }
688
+ }
689
+ return { synced, errors };
222
690
  },
223
691
  });
224
692
  /**
@@ -239,7 +707,7 @@ export const syncGarmin = action({
239
707
  const connection = await ctx.runQuery(internal.private.getConnectionByProvider, { userId: args.userId, provider: "GARMIN" });
240
708
  if (!connection) {
241
709
  throw new Error(`No Garmin connection found for user "${args.userId}". ` +
242
- "Call connectGarmin first.");
710
+ "Connect to Garmin first via getGarminAuthUrl.");
243
711
  }
244
712
  if (!connection.active) {
245
713
  throw new Error(`Garmin connection for user "${args.userId}" is inactive. Reconnect first.`);
@@ -303,155 +771,10 @@ export const syncGarmin = action({
303
771
  return result;
304
772
  },
305
773
  });
306
- /**
307
- * Disconnect a user from Garmin.
308
- *
309
- * Deregisters the user via the Garmin API (best-effort), deletes stored
310
- * tokens, and sets the connection to inactive.
311
- */
312
- export const disconnectGarmin = action({
313
- args: {
314
- userId: v.string(),
315
- },
316
- handler: async (ctx, args) => {
317
- const connection = await ctx.runQuery(internal.private.getConnectionByProvider, { userId: args.userId, provider: "GARMIN" });
318
- if (!connection) {
319
- throw new Error(`No Garmin connection found for user "${args.userId}".`);
320
- }
321
- const connectionId = connection._id;
322
- // Best-effort: deregister user at Garmin
323
- const tokenDoc = await ctx.runQuery(internal.garmin.private.getTokens, {
324
- connectionId,
325
- });
326
- if (tokenDoc) {
327
- try {
328
- const wellnessClient = createWellnessClient(tokenDoc.accessToken);
329
- await sdkDereg({ client: wellnessClient });
330
- }
331
- catch {
332
- // Deregistration is best-effort; proceed with local cleanup
333
- }
334
- }
335
- const _deleted = await ctx.runMutation(internal.garmin.private.deleteTokens, { connectionId });
336
- const _disconnected = await ctx.runMutation(api.public.disconnect, {
337
- userId: args.userId,
338
- provider: "GARMIN",
339
- });
340
- return null;
341
- },
342
- });
343
- // ─── Training API ────────────────────────────────────────────────────────────
344
- /**
345
- * Push a planned workout from Soma's DB to Garmin Connect.
346
- *
347
- * Reads the planned workout document, transforms it to Garmin Training API V2
348
- * format, creates the workout at Garmin, and optionally schedules it if a
349
- * `planned_date` is set in the metadata.
350
- *
351
- * Returns the Garmin workout ID and schedule ID (if scheduled).
352
- */
353
- export const pushPlannedWorkout = action({
354
- args: {
355
- userId: v.string(),
356
- clientId: v.string(),
357
- clientSecret: v.string(),
358
- plannedWorkoutId: v.string(),
359
- workoutProvider: v.optional(v.string()),
360
- },
361
- handler: async (ctx, args) => {
362
- const connection = await ctx.runQuery(internal.private.getConnectionByProvider, { userId: args.userId, provider: "GARMIN" });
363
- if (!connection) {
364
- throw new Error(`No Garmin connection found for user "${args.userId}". ` +
365
- "Call connectGarmin first.");
366
- }
367
- if (!connection.active) {
368
- throw new Error(`Garmin connection for user "${args.userId}" is inactive. Reconnect first.`);
369
- }
370
- const connectionId = connection._id;
371
- const tokenDoc = await ctx.runQuery(internal.garmin.private.getTokens, {
372
- connectionId,
373
- });
374
- if (!tokenDoc) {
375
- throw new Error("No Garmin tokens found for this connection. " +
376
- "The connection may have been created before token storage was available.");
377
- }
378
- // Always force-refresh the token for Training API calls to rule out
379
- // stale tokens (the initial sync swallows 401 errors silently).
380
- let accessToken = tokenDoc.accessToken;
381
- if (tokenDoc.refreshToken) {
382
- try {
383
- const refreshed = await refreshToken({
384
- clientId: args.clientId,
385
- clientSecret: args.clientSecret,
386
- refreshToken: tokenDoc.refreshToken,
387
- });
388
- accessToken = refreshed.access_token;
389
- const nowSeconds = Math.floor(Date.now() / 1000);
390
- const newExpiresAt = nowSeconds + refreshed.expires_in;
391
- const _refreshed = await ctx.runMutation(internal.garmin.private.storeTokens, {
392
- connectionId,
393
- accessToken: refreshed.access_token,
394
- refreshToken: refreshed.refresh_token,
395
- expiresAt: newExpiresAt,
396
- });
397
- }
398
- catch (refreshErr) {
399
- throw new Error(`Garmin token refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}. ` +
400
- "The user may need to reconnect their Garmin account.");
401
- }
402
- }
403
- const plannedWorkout = await ctx.runQuery(api.public.getPlannedWorkout, { plannedWorkoutId: args.plannedWorkoutId });
404
- if (!plannedWorkout) {
405
- throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
406
- }
407
- const providerName = args.workoutProvider ?? "Soma";
408
- const garminWorkout = transformPlannedWorkoutToGarmin(plannedWorkout, providerName);
409
- const trainingClient = createTrainingClient(accessToken);
410
- const { data: created, error: createError } = await sdkCreateWorkoutV2({
411
- client: trainingClient,
412
- body: garminWorkout,
413
- });
414
- if (createError || !created) {
415
- throw new Error(`Garmin API error creating workout: ${createError ? JSON.stringify(createError) : "No data"}`);
416
- }
417
- if (!created.workoutId) {
418
- throw new Error("Garmin API did not return a workoutId after creation.");
419
- }
420
- let garminScheduleId = null;
421
- const plannedDate = plannedWorkout.metadata?.planned_date;
422
- if (plannedDate) {
423
- const { data: scheduleId, error: scheduleError } = await sdkCreateWorkoutSchedule({
424
- client: trainingClient,
425
- body: { workoutId: Number(created.workoutId), date: plannedDate },
426
- });
427
- if (scheduleError) {
428
- throw new Error(`Garmin API error creating schedule: ${JSON.stringify(scheduleError)}`);
429
- }
430
- garminScheduleId = scheduleId ?? null;
431
- }
432
- // Store the Garmin workout/schedule IDs back on the planned workout
433
- // so the host app can match completed activities to planned sessions.
434
- const _ingested = await ctx.runMutation(api.public.ingestPlannedWorkout, {
435
- ...plannedWorkout,
436
- _id: undefined,
437
- _creationTime: undefined,
438
- metadata: {
439
- ...plannedWorkout.metadata,
440
- provider_workout_id: String(created.workoutId),
441
- provider_schedule_id: garminScheduleId != null ? String(garminScheduleId) : undefined,
442
- },
443
- });
444
- return {
445
- garminWorkoutId: created.workoutId,
446
- garminScheduleId,
447
- };
448
- },
449
- });
450
- // ─── Sync Engine ────────────────────────────────────────────────────────────
451
774
  /**
452
775
  * Fetch and ingest all Garmin wellness data types for a time range.
453
776
  *
454
- * Called by the public actions (connectGarmin, completeGarminOAuth, syncGarmin)
777
+ * Called by syncGarmin after obtaining a valid access token.
455
778
  * after obtaining a valid access token.
456
779
  */
457
780
  export const syncAllTypes = action({
@@ -827,4 +1150,111 @@ export const syncAllTypes = action({
827
1150
  return { synced, errors };
828
1151
  },
829
1152
  });
1153
+ // ─── Push ───────────────────────────────────────────────────────────────────
1154
+ /**
1155
+ * Push a planned workout from Soma's DB to Garmin Connect.
1156
+ *
1157
+ * Reads the planned workout document, transforms it to Garmin Training API V2
1158
+ * format, creates the workout at Garmin, and optionally schedules it if a
1159
+ * `planned_date` is set in the metadata.
1160
+ *
1161
+ * Returns the Garmin workout ID and schedule ID (if scheduled).
1162
+ */
1163
+ export const pushPlannedWorkout = action({
1164
+ args: {
1165
+ userId: v.string(),
1166
+ clientId: v.string(),
1167
+ clientSecret: v.string(),
1168
+ plannedWorkoutId: v.string(),
1169
+ workoutProvider: v.optional(v.string()),
1170
+ },
1171
+ handler: async (ctx, args) => {
1172
+ const connection = await ctx.runQuery(internal.private.getConnectionByProvider, { userId: args.userId, provider: "GARMIN" });
1173
+ if (!connection) {
1174
+ throw new Error(`No Garmin connection found for user "${args.userId}". ` +
1175
+ "Connect to Garmin first via getGarminAuthUrl.");
1176
+ }
1177
+ if (!connection.active) {
1178
+ throw new Error(`Garmin connection for user "${args.userId}" is inactive. Reconnect first.`);
1179
+ }
1180
+ const connectionId = connection._id;
1181
+ const tokenDoc = await ctx.runQuery(internal.garmin.private.getTokens, {
1182
+ connectionId,
1183
+ });
1184
+ if (!tokenDoc) {
1185
+ throw new Error("No Garmin tokens found for this connection. " +
1186
+ "The connection may have been created before token storage was available.");
1187
+ }
1188
+ // Always force-refresh the token for Training API calls to rule out
1189
+ // stale tokens (the initial sync swallows 401 errors silently).
1190
+ let accessToken = tokenDoc.accessToken;
1191
+ if (tokenDoc.refreshToken) {
1192
+ try {
1193
+ const refreshed = await refreshToken({
1194
+ clientId: args.clientId,
1195
+ clientSecret: args.clientSecret,
1196
+ refreshToken: tokenDoc.refreshToken,
1197
+ });
1198
+ accessToken = refreshed.access_token;
1199
+ const nowSeconds = Math.floor(Date.now() / 1000);
1200
+ const newExpiresAt = nowSeconds + refreshed.expires_in;
1201
+ const _refreshed = await ctx.runMutation(internal.garmin.private.storeTokens, {
1202
+ connectionId,
1203
+ accessToken: refreshed.access_token,
1204
+ refreshToken: refreshed.refresh_token,
1205
+ expiresAt: newExpiresAt,
1206
+ });
1207
+ }
1208
+ catch (refreshErr) {
1209
+ throw new Error(`Garmin token refresh failed: ${refreshErr instanceof Error ? refreshErr.message : String(refreshErr)}. ` +
1210
+ "The user may need to reconnect their Garmin account.");
1211
+ }
1212
+ }
1213
+ const plannedWorkout = await ctx.runQuery(api.public.getPlannedWorkout, { plannedWorkoutId: args.plannedWorkoutId });
1214
+ if (!plannedWorkout) {
1215
+ throw new Error(`Planned workout "${args.plannedWorkoutId}" not found.`);
1216
+ }
1217
+ const providerName = args.workoutProvider ?? "Soma";
1218
+ const garminWorkout = transformPlannedWorkoutToGarmin(plannedWorkout, providerName);
1219
+ const trainingClient = createTrainingClient(accessToken);
1220
+ const { data: created, error: createError } = await sdkCreateWorkoutV2({
1221
+ client: trainingClient,
1222
+ body: garminWorkout,
1223
+ });
1224
+ if (createError || !created) {
1225
+ throw new Error(`Garmin API error creating workout: ${createError ? JSON.stringify(createError) : "No data"}`);
1226
+ }
1227
+ if (!created.workoutId) {
1228
+ throw new Error("Garmin API did not return a workoutId after creation.");
1229
+ }
1230
+ let garminScheduleId = null;
1231
+ const plannedDate = plannedWorkout.metadata?.planned_date;
1232
+ if (plannedDate) {
1233
+ const { data: scheduleId, error: scheduleError } = await sdkCreateWorkoutSchedule({
1234
+ client: trainingClient,
1235
+ body: { workoutId: Number(created.workoutId), date: plannedDate },
1236
+ });
1237
+ if (scheduleError) {
1238
+ throw new Error(`Garmin API error creating schedule: ${JSON.stringify(scheduleError)}`);
1239
+ }
1240
+ garminScheduleId = scheduleId ?? null;
1241
+ }
1242
+ // Store the Garmin workout/schedule IDs back on the planned workout
1243
+ // so the host app can match completed activities to planned sessions.
1244
+ const _ingested = await ctx.runMutation(api.public.ingestPlannedWorkout, {
1245
+ ...plannedWorkout,
1246
+ _id: undefined,
1247
+ _creationTime: undefined,
1248
+ metadata: {
1249
+ ...plannedWorkout.metadata,
1250
+ provider_workout_id: String(created.workoutId),
1251
+ provider_schedule_id: garminScheduleId != null ? String(garminScheduleId) : undefined,
1252
+ },
1253
+ });
1254
+ return {
1255
+ garminWorkoutId: created.workoutId,
1256
+ garminScheduleId,
1257
+ };
1258
+ },
1259
+ });
830
1260
  //# sourceMappingURL=public.js.map