@nativesquare/soma 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,44 @@
1
1
  import type { ComponentApi } from "../component/_generated/component.js";
2
- import type { ActionCtx, MutationCtx, QueryCtx } from "./types.js";
2
+ import type {
3
+ MutationCtx,
4
+ QueryCtx,
5
+ SomaStravaConfig,
6
+ SomaGarminConfig,
7
+ IngestArgs,
8
+ ListTimeRangeArgs,
9
+ PaginateTimeRangeArgs,
10
+ RegisterRoutesOptions,
11
+ GarminWebhookEventName,
12
+ GarminWebhookEvent,
13
+ } from "./types.js";
14
+ export type {
15
+ ActionCtx,
16
+ SomaStravaConfig,
17
+ SomaGarminConfig,
18
+ IngestArgs,
19
+ TimeRangeArgs,
20
+ ListTimeRangeArgs,
21
+ PaginateTimeRangeArgs,
22
+ StravaOAuthOptions,
23
+ StravaConnectEvent,
24
+ GarminConnectEvent,
25
+ GarminWebhookEvent,
26
+ GarminOAuthOptions,
27
+ GarminWebhookEventName,
28
+ GarminWebhookHandler,
29
+ GarminWebhookOptions,
30
+ RegisterRoutesOptions,
31
+ } from "./types.js";
3
32
  import {
4
33
  httpActionGeneric,
5
34
  type FunctionReference,
6
- type GenericActionCtx,
7
- type GenericDataModel,
8
35
  type HttpRouter,
9
36
  } from "convex/server";
37
+ import { SomaGarmin } from "./garmin.js";
38
+ import { SomaStrava } from "./strava.js";
39
+
40
+ export { SomaGarmin } from "./garmin.js";
41
+ export { SomaStrava } from "./strava.js";
10
42
 
11
43
  export type SomaComponent = ComponentApi;
12
44
 
@@ -17,34 +49,6 @@ export const STRAVA_CALLBACK_PATH = "/api/strava/callback";
17
49
  export const GARMIN_OAUTH_CALLBACK_PATH = "/api/garmin/callback";
18
50
  export const GARMIN_WEBHOOK_BASE_PATH = "/api/garmin/webhook";
19
51
 
20
- /**
21
- * Configuration for the Strava integration.
22
- *
23
- * If not provided to the constructor, the Soma class will attempt to
24
- * read `STRAVA_CLIENT_ID`, `STRAVA_CLIENT_SECRET`, and `STRAVA_BASE_URL`
25
- * from environment variables automatically.
26
- */
27
- export interface SomaStravaConfig {
28
- /** Your Strava application's Client ID. */
29
- clientId: string;
30
- /** Your Strava application's Client Secret. */
31
- clientSecret: string;
32
- }
33
-
34
- /**
35
- * Configuration for the Garmin integration.
36
- *
37
- * If not provided to the constructor, the Soma class will attempt to
38
- * read `GARMIN_CLIENT_ID` and `GARMIN_CLIENT_SECRET` from
39
- * environment variables automatically.
40
- */
41
- export interface SomaGarminConfig {
42
- /** Your Garmin application's Client ID. */
43
- clientId: string;
44
- /** Your Garmin application's Client Secret. */
45
- clientSecret: string;
46
- }
47
-
48
52
  /**
49
53
  * Client class for the @nativesquare/soma Convex component.
50
54
  *
@@ -52,7 +56,7 @@ export interface SomaGarminConfig {
52
56
  * and querying normalized health & fitness data.
53
57
  *
54
58
  * All capabilities are also accessible via direct component function calls:
55
- * `ctx.runMutation(components.soma.public.connect, { userId, provider: "GARMIN" })`
59
+ * `ctx.runQuery(components.soma.public.listActivities, { userId: "user_123" })`
56
60
  *
57
61
  * @example
58
62
  * ```ts
@@ -61,37 +65,42 @@ export interface SomaGarminConfig {
61
65
  * import { components } from "./_generated/api";
62
66
  *
63
67
  * // Zero config if env vars are set in Convex dashboard:
64
- * // STRAVA_CLIENT_ID, STRAVA_CLIENT_SECRET, STRAVA_BASE_URL (optional)
68
+ * // STRAVA_CLIENT_ID, STRAVA_CLIENT_SECRET
69
+ * // GARMIN_CLIENT_ID, GARMIN_CLIENT_SECRET
65
70
  * const soma = new Soma(components.soma);
66
71
  *
67
- * // Or with explicit Strava config:
72
+ * // Or with explicit config:
68
73
  * // const soma = new Soma(components.soma, {
69
74
  * // strava: { clientId: "...", clientSecret: "..." },
75
+ * // garmin: { clientId: "...", clientSecret: "..." },
70
76
  * // });
71
77
  *
72
- * // Connect a user to a provider:
73
- * const connectionId = await soma.connect(ctx, {
74
- * userId: "user_123",
75
- * provider: "GARMIN",
76
- * });
77
- *
78
78
  * // Start Strava OAuth (redirects user, callback handled by registerRoutes):
79
- * const { authUrl } = await soma.getStravaAuthUrl(ctx, {
79
+ * const { authUrl } = await soma.strava.getAuthUrl(ctx, {
80
80
  * userId: "user_123",
81
81
  * redirectUri: "https://your-app.convex.site/api/strava/callback",
82
82
  * });
83
+ *
84
+ * // Pull all Garmin data:
85
+ * await soma.garmin.pullAll(ctx, { userId: "user_123" });
83
86
  * ```
84
87
  */
85
88
  export class Soma {
86
89
  private stravaConfig?: SomaStravaConfig;
87
90
  private garminConfig?: SomaGarminConfig;
88
91
 
92
+ public readonly garmin: SomaGarmin;
93
+ public readonly strava: SomaStrava;
94
+
89
95
  constructor(
90
96
  public component: SomaComponent,
91
97
  options?: { strava?: SomaStravaConfig; garmin?: SomaGarminConfig },
92
98
  ) {
93
99
  this.stravaConfig = options?.strava ?? this.readStravaEnv();
94
100
  this.garminConfig = options?.garmin ?? this.readGarminEnv();
101
+
102
+ this.garmin = new SomaGarmin(this.component, () => this.requireGarminConfig());
103
+ this.strava = new SomaStrava(this.component, () => this.requireStravaConfig());
95
104
  }
96
105
 
97
106
  /**
@@ -147,66 +156,6 @@ export class Soma {
147
156
  return this.garminConfig;
148
157
  }
149
158
 
150
- // ─── Connect / Disconnect ───────────────────────────────────────────────────
151
-
152
- /**
153
- * Connect a user to a wearable provider.
154
- *
155
- * Creates the connection if it doesn't exist, or re-activates it if it was
156
- * previously disconnected. Idempotent — calling twice is a no-op.
157
- *
158
- * Use this when the host app has completed the provider's auth flow and
159
- * wants to register the connection in Soma.
160
- *
161
- * @param ctx - Mutation context from the host app
162
- * @param args.userId - The host app's user identifier (Clerk ID, etc.)
163
- * @param args.provider - The wearable provider name ("GARMIN", "FITBIT", "OURA", etc.)
164
- * @returns The connection document ID
165
- *
166
- * @example
167
- * ```ts
168
- * // "Connect to Garmin" button handler
169
- * const connectionId = await soma.connect(ctx, {
170
- * userId: "user_123",
171
- * provider: "GARMIN",
172
- * });
173
- * ```
174
- */
175
- async connect(
176
- ctx: MutationCtx,
177
- args: { userId: string; provider: string },
178
- ): Promise<string> {
179
- return await ctx.runMutation(this.component.public.connect, args);
180
- }
181
-
182
- /**
183
- * Disconnect a user from a wearable provider.
184
- *
185
- * Sets the connection to inactive. Does not delete any synced data,
186
- * so re-connecting later preserves historical records.
187
- *
188
- * @param ctx - Mutation context from the host app
189
- * @param args.userId - The host app's user identifier
190
- * @param args.provider - The wearable provider name
191
- *
192
- * @throws Error if no connection exists for the given user–provider pair
193
- *
194
- * @example
195
- * ```ts
196
- * // "Disconnect Garmin" button handler
197
- * await soma.disconnect(ctx, {
198
- * userId: "user_123",
199
- * provider: "GARMIN",
200
- * });
201
- * ```
202
- */
203
- async disconnect(
204
- ctx: MutationCtx,
205
- args: { userId: string; provider: string },
206
- ): Promise<null> {
207
- return await ctx.runMutation(this.component.public.disconnect, args);
208
- }
209
-
210
159
  // ─── Connection Queries ─────────────────────────────────────────────────────
211
160
 
212
161
  /**
@@ -812,7 +761,7 @@ export class Soma {
812
761
  ) {
813
762
  return await ctx.runMutation(
814
763
  this.component.public.deletePlannedWorkout,
815
- args as never,
764
+ args,
816
765
  );
817
766
  }
818
767
 
@@ -828,563 +777,10 @@ export class Soma {
828
777
  ) {
829
778
  return await ctx.runQuery(
830
779
  this.component.public.getPlannedWorkout,
831
- args as never,
780
+ args,
832
781
  );
833
782
  }
834
783
 
835
- // ─── Strava Integration ──────────────────────────────────────────────────────
836
- // High-level methods that handle OAuth, token storage, and data syncing
837
- // for Strava. Requires Strava credentials to be configured either via
838
- // environment variables or the constructor.
839
-
840
- /**
841
- * Generate a Strava OAuth authorization URL.
842
- *
843
- * The state parameter is stored inside the component automatically,
844
- * and the callback handler registered by `registerRoutes` will
845
- * complete the flow without further host-app intervention.
846
- *
847
- * @param ctx - Action context from the host app
848
- * @param opts.userId - The host app's user identifier
849
- * @param opts.redirectUri - The URL Strava will redirect to after authorization
850
- * @param opts.scope - Comma-separated Strava OAuth scopes (default: "read,activity:read_all,profile:read_all")
851
- * @returns `{ authUrl, state }`
852
- *
853
- * @example
854
- * ```ts
855
- * const { authUrl } = await soma.getStravaAuthUrl(ctx, {
856
- * userId: "user_123",
857
- * redirectUri: "https://your-app.convex.site/api/strava/callback",
858
- * });
859
- * // Redirect user to authUrl — the callback is handled automatically
860
- * ```
861
- */
862
- async getStravaAuthUrl(
863
- ctx: ActionCtx,
864
- opts: { userId: string; redirectUri: string; scope?: string },
865
- ) {
866
- const config = this.requireStravaConfig();
867
- return await ctx.runAction(this.component.strava.public.getStravaAuthUrl, {
868
- clientId: config.clientId,
869
- redirectUri: opts.redirectUri,
870
- scope: opts.scope,
871
- userId: opts.userId,
872
- });
873
- }
874
-
875
-
876
- /**
877
- * Sync activities from Strava for an already-connected user.
878
- *
879
- * Automatically refreshes the access token if expired. Fetches the
880
- * athlete profile and activities, transforms them, and ingests into Soma.
881
- *
882
- * @param ctx - Action context from the host app
883
- * @param args.userId - The host app's user identifier
884
- * @param args.after - Only sync activities after this Unix epoch timestamp (for incremental sync)
885
- * @returns `{ synced, errors }`
886
- *
887
- * @example
888
- * ```ts
889
- * export const syncStrava = action({
890
- * args: { userId: v.string() },
891
- * handler: async (ctx, { userId }) => {
892
- * return await soma.syncStrava(ctx, { userId });
893
- * },
894
- * });
895
- * ```
896
- */
897
- async syncStrava(
898
- ctx: ActionCtx,
899
- args: { userId: string; after?: number },
900
- ) {
901
- const config = this.requireStravaConfig();
902
- return await ctx.runAction(this.component.strava.public.syncStrava, {
903
- ...args,
904
- clientId: config.clientId,
905
- clientSecret: config.clientSecret,
906
- });
907
- }
908
-
909
- /**
910
- * Disconnect a user from Strava.
911
- *
912
- * Revokes the token at Strava (best-effort), deletes stored tokens,
913
- * and sets the connection to inactive.
914
- *
915
- * @param ctx - Action context from the host app
916
- * @param args.userId - The host app's user identifier
917
- *
918
- * @example
919
- * ```ts
920
- * export const disconnectStrava = action({
921
- * args: { userId: v.string() },
922
- * handler: async (ctx, { userId }) => {
923
- * await soma.disconnectStrava(ctx, { userId });
924
- * },
925
- * });
926
- * ```
927
- */
928
- async disconnectStrava(
929
- ctx: ActionCtx,
930
- args: { userId: string },
931
- ) {
932
- const config = this.requireStravaConfig();
933
- return await ctx.runAction(this.component.strava.public.disconnectStrava, {
934
- ...args,
935
- clientId: config.clientId,
936
- clientSecret: config.clientSecret,
937
- });
938
- }
939
-
940
- // ─── Garmin ──────────────────────────────────────────────────────
941
-
942
- async getGarminAuthUrl(
943
- ctx: ActionCtx,
944
- opts: { userId: string; redirectUri?: string },
945
- ) {
946
- const config = this.requireGarminConfig();
947
- return await ctx.runAction(this.component.garmin.public.getGarminAuthUrl, {
948
- clientId: config.clientId,
949
- redirectUri: opts.redirectUri,
950
- userId: opts.userId,
951
- });
952
- }
953
-
954
- async disconnectGarmin(
955
- ctx: ActionCtx,
956
- args: { userId: string },
957
- ) {
958
- return await ctx.runAction(this.component.garmin.public.disconnectGarmin, args);
959
- }
960
-
961
- async pullGarminActivities(
962
- ctx: ActionCtx,
963
- args: {
964
- userId: string;
965
- startTimeInSeconds?: number;
966
- endTimeInSeconds?: number;
967
- },
968
- ) {
969
- const config = this.requireGarminConfig();
970
- return await ctx.runAction(this.component.garmin.public.pullActivities, {
971
- ...args,
972
- clientId: config.clientId,
973
- clientSecret: config.clientSecret,
974
- });
975
- }
976
-
977
- async pullGarminDailies(
978
- ctx: ActionCtx,
979
- args: {
980
- userId: string;
981
- startTimeInSeconds?: number;
982
- endTimeInSeconds?: number;
983
- },
984
- ) {
985
- const config = this.requireGarminConfig();
986
- return await ctx.runAction(this.component.garmin.public.pullDailies, {
987
- ...args,
988
- clientId: config.clientId,
989
- clientSecret: config.clientSecret,
990
- });
991
- }
992
-
993
- async pullGarminSleep(
994
- ctx: ActionCtx,
995
- args: {
996
- userId: string;
997
- startTimeInSeconds?: number;
998
- endTimeInSeconds?: number;
999
- },
1000
- ) {
1001
- const config = this.requireGarminConfig();
1002
- return await ctx.runAction(this.component.garmin.public.pullSleep, {
1003
- ...args,
1004
- clientId: config.clientId,
1005
- clientSecret: config.clientSecret,
1006
- });
1007
- }
1008
-
1009
- async pullGarminBody(
1010
- ctx: ActionCtx,
1011
- args: {
1012
- userId: string;
1013
- startTimeInSeconds?: number;
1014
- endTimeInSeconds?: number;
1015
- },
1016
- ) {
1017
- const config = this.requireGarminConfig();
1018
- return await ctx.runAction(this.component.garmin.public.pullBody, {
1019
- ...args,
1020
- clientId: config.clientId,
1021
- clientSecret: config.clientSecret,
1022
- });
1023
- }
1024
-
1025
- async pullGarminMenstruation(
1026
- ctx: ActionCtx,
1027
- args: {
1028
- userId: string;
1029
- startTimeInSeconds?: number;
1030
- endTimeInSeconds?: number;
1031
- },
1032
- ) {
1033
- const config = this.requireGarminConfig();
1034
- return await ctx.runAction(this.component.garmin.public.pullMenstruation, {
1035
- ...args,
1036
- clientId: config.clientId,
1037
- clientSecret: config.clientSecret,
1038
- });
1039
- }
1040
-
1041
- async pullGarminBloodPressures(
1042
- ctx: ActionCtx,
1043
- args: {
1044
- userId: string;
1045
- startTimeInSeconds?: number;
1046
- endTimeInSeconds?: number;
1047
- },
1048
- ) {
1049
- const config = this.requireGarminConfig();
1050
- return await ctx.runAction(this.component.garmin.public.pullBloodPressures, {
1051
- ...args,
1052
- clientId: config.clientId,
1053
- clientSecret: config.clientSecret,
1054
- });
1055
- }
1056
-
1057
- async pullGarminSkinTemperature(
1058
- ctx: ActionCtx,
1059
- args: {
1060
- userId: string;
1061
- startTimeInSeconds?: number;
1062
- endTimeInSeconds?: number;
1063
- },
1064
- ) {
1065
- const config = this.requireGarminConfig();
1066
- return await ctx.runAction(this.component.garmin.public.pullSkinTemperature, {
1067
- ...args,
1068
- clientId: config.clientId,
1069
- clientSecret: config.clientSecret,
1070
- });
1071
- }
1072
-
1073
- async pullGarminUserMetrics(
1074
- ctx: ActionCtx,
1075
- args: {
1076
- userId: string;
1077
- startTimeInSeconds?: number;
1078
- endTimeInSeconds?: number;
1079
- },
1080
- ) {
1081
- const config = this.requireGarminConfig();
1082
- return await ctx.runAction(this.component.garmin.public.pullUserMetrics, {
1083
- ...args,
1084
- clientId: config.clientId,
1085
- clientSecret: config.clientSecret,
1086
- });
1087
- }
1088
-
1089
- async pullGarminHRV(
1090
- ctx: ActionCtx,
1091
- args: {
1092
- userId: string;
1093
- startTimeInSeconds?: number;
1094
- endTimeInSeconds?: number;
1095
- },
1096
- ) {
1097
- const config = this.requireGarminConfig();
1098
- return await ctx.runAction(this.component.garmin.public.pullHRV, {
1099
- ...args,
1100
- clientId: config.clientId,
1101
- clientSecret: config.clientSecret,
1102
- });
1103
- }
1104
-
1105
- async pullGarminStressDetails(
1106
- ctx: ActionCtx,
1107
- args: {
1108
- userId: string;
1109
- startTimeInSeconds?: number;
1110
- endTimeInSeconds?: number;
1111
- },
1112
- ) {
1113
- const config = this.requireGarminConfig();
1114
- return await ctx.runAction(this.component.garmin.public.pullStressDetails, {
1115
- ...args,
1116
- clientId: config.clientId,
1117
- clientSecret: config.clientSecret,
1118
- });
1119
- }
1120
-
1121
- async pullGarminPulseOx(
1122
- ctx: ActionCtx,
1123
- args: {
1124
- userId: string;
1125
- startTimeInSeconds?: number;
1126
- endTimeInSeconds?: number;
1127
- },
1128
- ) {
1129
- const config = this.requireGarminConfig();
1130
- return await ctx.runAction(this.component.garmin.public.pullPulseOx, {
1131
- ...args,
1132
- clientId: config.clientId,
1133
- clientSecret: config.clientSecret,
1134
- });
1135
- }
1136
-
1137
- async pullGarminRespiration(
1138
- ctx: ActionCtx,
1139
- args: {
1140
- userId: string;
1141
- startTimeInSeconds?: number;
1142
- endTimeInSeconds?: number;
1143
- },
1144
- ) {
1145
- const config = this.requireGarminConfig();
1146
- return await ctx.runAction(this.component.garmin.public.pullRespiration, {
1147
- ...args,
1148
- clientId: config.clientId,
1149
- clientSecret: config.clientSecret,
1150
- });
1151
- }
1152
-
1153
- async pullGarminAll(
1154
- ctx: ActionCtx,
1155
- args: {
1156
- userId: string;
1157
- startTimeInSeconds?: number;
1158
- endTimeInSeconds?: number;
1159
- },
1160
- ) {
1161
- const config = this.requireGarminConfig();
1162
- return await ctx.runAction(this.component.garmin.public.pullAll, {
1163
- ...args,
1164
- clientId: config.clientId,
1165
- clientSecret: config.clientSecret,
1166
- });
1167
- }
1168
-
1169
- async pushPlannedWorkoutToGarmin(
1170
- ctx: ActionCtx,
1171
- args: {
1172
- userId: string;
1173
- plannedWorkoutId: string;
1174
- workoutProvider?: string;
1175
- },
1176
- ) {
1177
- const config = this.requireGarminConfig();
1178
- return await ctx.runAction(this.component.garmin.public.pushPlannedWorkout, {
1179
- ...args,
1180
- clientId: config.clientId,
1181
- clientSecret: config.clientSecret,
1182
- });
1183
- }
1184
-
1185
- async pushWorkoutToGarmin(
1186
- ctx: ActionCtx,
1187
- args: {
1188
- userId: string;
1189
- plannedWorkoutId: string;
1190
- workoutProvider?: string;
1191
- },
1192
- ) {
1193
- const config = this.requireGarminConfig();
1194
- return await ctx.runAction(this.component.garmin.public.pushWorkout, {
1195
- ...args,
1196
- clientId: config.clientId,
1197
- clientSecret: config.clientSecret,
1198
- });
1199
- }
1200
-
1201
- async pushScheduleToGarmin(
1202
- ctx: ActionCtx,
1203
- args: {
1204
- userId: string;
1205
- plannedWorkoutId: string;
1206
- date?: string;
1207
- },
1208
- ) {
1209
- const config = this.requireGarminConfig();
1210
- return await ctx.runAction(this.component.garmin.public.pushSchedule, {
1211
- ...args,
1212
- clientId: config.clientId,
1213
- clientSecret: config.clientSecret,
1214
- });
1215
- }
1216
-
1217
- async deleteWorkoutFromGarmin(
1218
- ctx: ActionCtx,
1219
- args: {
1220
- userId: string;
1221
- plannedWorkoutId: string;
1222
- },
1223
- ) {
1224
- const config = this.requireGarminConfig();
1225
- return await ctx.runAction(this.component.garmin.public.deleteWorkout, {
1226
- ...args,
1227
- clientId: config.clientId,
1228
- clientSecret: config.clientSecret,
1229
- });
1230
- }
1231
-
1232
- async deleteScheduleFromGarmin(
1233
- ctx: ActionCtx,
1234
- args: {
1235
- userId: string;
1236
- plannedWorkoutId: string;
1237
- },
1238
- ) {
1239
- const config = this.requireGarminConfig();
1240
- return await ctx.runAction(this.component.garmin.public.deleteSchedule, {
1241
- ...args,
1242
- clientId: config.clientId,
1243
- clientSecret: config.clientSecret,
1244
- });
1245
- }
1246
- }
1247
-
1248
- // ─── Shared Types ────────────────────────────────────────────────────────────
1249
-
1250
- /**
1251
- * Common args shape for all ingestion methods.
1252
- *
1253
- * Requires `connectionId` and `userId` at minimum — additional fields
1254
- * come from the transformer output (e.g., `metadata`, `calories_data`, etc.)
1255
- * and are validated server-side by Convex validators.
1256
- */
1257
- type IngestArgs = {
1258
- connectionId: string;
1259
- userId: string;
1260
- } & Record<string, unknown>;
1261
-
1262
- /**
1263
- * Base args for time-range filtered queries.
1264
- *
1265
- * - `userId` is required for all health data queries.
1266
- * - `startTime` / `endTime` are optional ISO-8601 bounds on `metadata.start_time`.
1267
- */
1268
- type TimeRangeArgs = {
1269
- userId: string;
1270
- startTime?: string;
1271
- endTime?: string;
1272
- };
1273
-
1274
- /**
1275
- * Args for list (collect-all) queries with optional ordering and limit.
1276
- */
1277
- type ListTimeRangeArgs = TimeRangeArgs & {
1278
- order?: "asc" | "desc";
1279
- limit?: number;
1280
- };
1281
-
1282
- /**
1283
- * Args for paginated queries with Convex pagination options.
1284
- */
1285
- type PaginateTimeRangeArgs = TimeRangeArgs & {
1286
- paginationOpts: { numItems: number; cursor: string | null };
1287
- };
1288
-
1289
- // ─── Route Registration ──────────────────────────────────────────────────────
1290
-
1291
- /**
1292
- * Per-provider options for `registerRoutes`.
1293
- */
1294
- export interface StravaOAuthOptions {
1295
- /** HTTP path for the OAuth callback. @default "/api/strava/callback" */
1296
- path?: string;
1297
- /** Override STRAVA_CLIENT_ID env var. */
1298
- clientId?: string;
1299
- /** Override STRAVA_CLIENT_SECRET env var. */
1300
- clientSecret?: string;
1301
- /** URL to redirect the user to after a successful connection. */
1302
- redirectTo?: string;
1303
- /** Called after Strava OAuth completes and the connection is established. */
1304
- onComplete?: (
1305
- ctx: GenericActionCtx<GenericDataModel>,
1306
- event: StravaConnectEvent,
1307
- ) => Promise<void>;
1308
- }
1309
-
1310
- // ─── Strava Callback Event Types ────────────────────────────────────────────
1311
-
1312
- /** Data passed to `onComplete` after Strava OAuth completes. */
1313
- export interface StravaConnectEvent {
1314
- provider: "STRAVA";
1315
- userId: string;
1316
- connectionId: string;
1317
- }
1318
-
1319
- // ─── Garmin Callback Event Types ─────────────────────────────────────────────
1320
-
1321
- /** Data passed to `oauth.onComplete` after Garmin OAuth completes. */
1322
- export interface GarminConnectEvent {
1323
- provider: "GARMIN";
1324
- userId: string;
1325
- connectionId: string;
1326
- }
1327
-
1328
- /** Data passed to webhook `events` handlers and `onEvent` after data ingestion. */
1329
- export interface GarminWebhookEvent {
1330
- dataType: string;
1331
- processed: number;
1332
- errors: Array<{ type: string; id: string; error: string }>;
1333
- /** Users whose data was affected by this webhook. */
1334
- affectedUsers: Array<{ userId: string; connectionId: string }>;
1335
- }
1336
-
1337
- // ─── Garmin Route Options ───────────────────────────────────────────────────
1338
-
1339
- export interface GarminOAuthOptions {
1340
- /** HTTP path for the OAuth callback. @default "/api/garmin/callback" */
1341
- path?: string;
1342
- /** Override GARMIN_CLIENT_ID env var. */
1343
- clientId?: string;
1344
- /** Override GARMIN_CLIENT_SECRET env var. */
1345
- clientSecret?: string;
1346
- /** URL to redirect the user to after a successful connection. */
1347
- redirectTo?: string;
1348
- /** Called after Garmin OAuth completes and the connection is established. */
1349
- onComplete?: (
1350
- ctx: GenericActionCtx<GenericDataModel>,
1351
- event: GarminConnectEvent,
1352
- ) => Promise<void>;
1353
- }
1354
-
1355
- /** Webhook endpoint names matching the Garmin API data types. */
1356
- export type GarminWebhookEventName =
1357
- | "activities" | "activity-details" | "manually-updated-activities" | "move-iq"
1358
- | "blood-pressures" | "body-compositions" | "dailies" | "epochs"
1359
- | "health-snapshot" | "sleeps" | "hrv" | "stress" | "pulse-ox"
1360
- | "respiration" | "skin-temp" | "user-metrics" | "menstrual-cycle-tracking";
1361
-
1362
- /** Handler for a specific webhook event or the catch-all `onEvent`. */
1363
- export type GarminWebhookHandler = (
1364
- ctx: GenericActionCtx<GenericDataModel>,
1365
- event: GarminWebhookEvent,
1366
- ) => Promise<void>;
1367
-
1368
- export interface GarminWebhookOptions {
1369
- /** Base path prefix for all webhook routes. @default "/api/garmin/webhook" */
1370
- basePath?: string;
1371
- /** Called after every webhook payload is processed, regardless of data type. */
1372
- onEvent?: GarminWebhookHandler;
1373
- /** Per-data-type handlers. Only subscribe to the types you care about. */
1374
- events?: Partial<Record<GarminWebhookEventName, GarminWebhookHandler>>;
1375
- }
1376
-
1377
- export interface RegisterRoutesOptions {
1378
- strava?: {
1379
- /** OAuth callback configuration. */
1380
- oauth?: StravaOAuthOptions;
1381
- };
1382
- garmin?: {
1383
- /** OAuth callback configuration. */
1384
- oauth?: GarminOAuthOptions;
1385
- /** Webhook route configuration. Set to `false` to skip webhook registration. */
1386
- webhook?: GarminWebhookOptions | false;
1387
- };
1388
784
  }
1389
785
 
1390
786
  /**
@@ -1444,14 +840,18 @@ export interface RegisterRoutesOptions {
1444
840
  * },
1445
841
  * },
1446
842
  * webhook: {
1447
- * onEvent: async (ctx, event) => {
1448
- * // Catch-all: runs for every webhook
1449
- * console.log(`Garmin ${event.dataType}: ${event.processed} processed`);
1450
- * },
843
+ * // Only listed data types get an HTTP route registered.
844
+ * // Pass a handler for custom logic, or `true` for default processing.
1451
845
  * events: {
1452
846
  * "activities": async (ctx, event) => {
1453
- * // Runs only for activity webhooks
847
+ * // Custom side-effect after activity ingestion
1454
848
  * },
849
+ * "sleeps": true, // register route, default processing only
850
+ * "dailies": true,
851
+ * },
852
+ * // Optional catch-all, runs for every registered event
853
+ * onEvent: async (ctx, event) => {
854
+ * console.log(`Garmin ${event.dataType}: ${event.processed} processed`);
1455
855
  * },
1456
856
  * },
1457
857
  * },
@@ -1637,8 +1037,8 @@ export function registerRoutes(
1637
1037
  });
1638
1038
 
1639
1039
  // ── Garmin Webhook Routes ──────────────────────────────────
1640
- if (garminOpts.webhook !== false) {
1641
- const webhookCfg = typeof garminOpts.webhook === "object" ? garminOpts.webhook : {};
1040
+ const webhookCfg = typeof garminOpts.webhook === "object" ? garminOpts.webhook : undefined;
1041
+ if (webhookCfg?.events) {
1642
1042
  const webhookBase = webhookCfg.basePath ?? GARMIN_WEBHOOK_BASE_PATH;
1643
1043
 
1644
1044
  const webhookRoutes: Array<{
@@ -1669,6 +1069,11 @@ export function registerRoutes(
1669
1069
  ];
1670
1070
 
1671
1071
  for (const route of webhookRoutes) {
1072
+ const dataType = route.suffix.slice(1) as GarminWebhookEventName;
1073
+
1074
+ // Only register routes the host app explicitly opted into
1075
+ if (!webhookCfg.events?.[dataType]) continue;
1076
+
1672
1077
  http.route({
1673
1078
  path: `${webhookBase}${route.suffix}`,
1674
1079
  method: "POST",
@@ -1692,7 +1097,6 @@ export function registerRoutes(
1692
1097
  }
1693
1098
 
1694
1099
  if (result) {
1695
- const dataType = route.suffix.slice(1) as GarminWebhookEventName;
1696
1100
  const event: GarminWebhookEvent = {
1697
1101
  dataType,
1698
1102
  processed: result.processed,
@@ -1701,7 +1105,7 @@ export function registerRoutes(
1701
1105
  };
1702
1106
 
1703
1107
  const specificHandler = webhookCfg.events?.[dataType];
1704
- if (specificHandler) {
1108
+ if (typeof specificHandler === "function") {
1705
1109
  try {
1706
1110
  await specificHandler(ctx, event);
1707
1111
  } catch (callbackError) {