@contractspec/integration.providers-impls 2.10.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +7 -1
  2. package/dist/impls/async-event-queue.d.ts +8 -0
  3. package/dist/impls/async-event-queue.js +47 -0
  4. package/dist/impls/health/base-health-provider.d.ts +64 -13
  5. package/dist/impls/health/base-health-provider.js +506 -156
  6. package/dist/impls/health/hybrid-health-providers.d.ts +34 -0
  7. package/dist/impls/health/hybrid-health-providers.js +1088 -0
  8. package/dist/impls/health/official-health-providers.d.ts +78 -0
  9. package/dist/impls/health/official-health-providers.js +968 -0
  10. package/dist/impls/health/provider-normalizers.d.ts +28 -0
  11. package/dist/impls/health/provider-normalizers.js +287 -0
  12. package/dist/impls/health/providers.d.ts +2 -39
  13. package/dist/impls/health/providers.js +895 -184
  14. package/dist/impls/health-provider-factory.js +1009 -196
  15. package/dist/impls/index.d.ts +6 -0
  16. package/dist/impls/index.js +1950 -278
  17. package/dist/impls/messaging-github.d.ts +17 -0
  18. package/dist/impls/messaging-github.js +110 -0
  19. package/dist/impls/messaging-slack.d.ts +14 -0
  20. package/dist/impls/messaging-slack.js +80 -0
  21. package/dist/impls/messaging-whatsapp-meta.d.ts +13 -0
  22. package/dist/impls/messaging-whatsapp-meta.js +52 -0
  23. package/dist/impls/messaging-whatsapp-twilio.d.ts +13 -0
  24. package/dist/impls/messaging-whatsapp-twilio.js +82 -0
  25. package/dist/impls/mistral-conversational.d.ts +23 -0
  26. package/dist/impls/mistral-conversational.js +476 -0
  27. package/dist/impls/mistral-conversational.session.d.ts +32 -0
  28. package/dist/impls/mistral-conversational.session.js +206 -0
  29. package/dist/impls/mistral-stt.d.ts +17 -0
  30. package/dist/impls/mistral-stt.js +167 -0
  31. package/dist/impls/provider-factory.d.ts +5 -1
  32. package/dist/impls/provider-factory.js +1943 -277
  33. package/dist/impls/stripe-payments.js +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1953 -278
  36. package/dist/messaging.d.ts +1 -0
  37. package/dist/messaging.js +3 -0
  38. package/dist/node/impls/async-event-queue.js +46 -0
  39. package/dist/node/impls/health/base-health-provider.js +506 -156
  40. package/dist/node/impls/health/hybrid-health-providers.js +1087 -0
  41. package/dist/node/impls/health/official-health-providers.js +967 -0
  42. package/dist/node/impls/health/provider-normalizers.js +286 -0
  43. package/dist/node/impls/health/providers.js +895 -184
  44. package/dist/node/impls/health-provider-factory.js +1009 -196
  45. package/dist/node/impls/index.js +1950 -278
  46. package/dist/node/impls/messaging-github.js +109 -0
  47. package/dist/node/impls/messaging-slack.js +79 -0
  48. package/dist/node/impls/messaging-whatsapp-meta.js +51 -0
  49. package/dist/node/impls/messaging-whatsapp-twilio.js +81 -0
  50. package/dist/node/impls/mistral-conversational.js +475 -0
  51. package/dist/node/impls/mistral-conversational.session.js +205 -0
  52. package/dist/node/impls/mistral-stt.js +166 -0
  53. package/dist/node/impls/provider-factory.js +1943 -277
  54. package/dist/node/impls/stripe-payments.js +1 -1
  55. package/dist/node/index.js +1953 -278
  56. package/dist/node/messaging.js +2 -0
  57. package/package.json +156 -12
@@ -1,4 +1,283 @@
1
+ // src/impls/health/provider-normalizers.ts
2
+ var DEFAULT_LIST_KEYS = [
3
+ "items",
4
+ "data",
5
+ "records",
6
+ "activities",
7
+ "workouts",
8
+ "sleep",
9
+ "biometrics",
10
+ "nutrition"
11
+ ];
12
+ function asRecord(value) {
13
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
14
+ return;
15
+ }
16
+ return value;
17
+ }
18
+ function asArray(value) {
19
+ return Array.isArray(value) ? value : undefined;
20
+ }
21
+ function readString(record, keys) {
22
+ if (!record)
23
+ return;
24
+ for (const key of keys) {
25
+ const value = record[key];
26
+ if (typeof value === "string" && value.trim().length > 0) {
27
+ return value;
28
+ }
29
+ }
30
+ return;
31
+ }
32
+ function readNumber(record, keys) {
33
+ if (!record)
34
+ return;
35
+ for (const key of keys) {
36
+ const value = record[key];
37
+ if (typeof value === "number" && Number.isFinite(value)) {
38
+ return value;
39
+ }
40
+ if (typeof value === "string" && value.trim().length > 0) {
41
+ const parsed = Number(value);
42
+ if (Number.isFinite(parsed)) {
43
+ return parsed;
44
+ }
45
+ }
46
+ }
47
+ return;
48
+ }
49
+ function readBoolean(record, keys) {
50
+ if (!record)
51
+ return;
52
+ for (const key of keys) {
53
+ const value = record[key];
54
+ if (typeof value === "boolean") {
55
+ return value;
56
+ }
57
+ }
58
+ return;
59
+ }
60
+ function extractList(payload, listKeys = DEFAULT_LIST_KEYS) {
61
+ const root = asRecord(payload);
62
+ if (!root) {
63
+ return asArray(payload)?.map((item) => asRecord(item)).filter((item) => Boolean(item)) ?? [];
64
+ }
65
+ for (const key of listKeys) {
66
+ const arrayValue = asArray(root[key]);
67
+ if (!arrayValue)
68
+ continue;
69
+ return arrayValue.map((item) => asRecord(item)).filter((item) => Boolean(item));
70
+ }
71
+ return [];
72
+ }
73
+ function extractPagination(payload) {
74
+ const root = asRecord(payload);
75
+ const nestedPagination = asRecord(root?.pagination);
76
+ const nextCursor = readString(nestedPagination, ["nextCursor", "next_cursor"]) ?? readString(root, [
77
+ "nextCursor",
78
+ "next_cursor",
79
+ "cursor",
80
+ "next_page_token"
81
+ ]);
82
+ const hasMore = readBoolean(nestedPagination, ["hasMore", "has_more"]) ?? readBoolean(root, ["hasMore", "has_more"]);
83
+ return {
84
+ nextCursor,
85
+ hasMore: hasMore ?? Boolean(nextCursor)
86
+ };
87
+ }
88
+ function toHealthActivity(item, context, fallbackType = "activity") {
89
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:${fallbackType}`;
90
+ const id = readString(item, ["id", "uuid", "workout_id"]) ?? `${context.providerKey}:activity:${externalId}`;
91
+ return {
92
+ id,
93
+ externalId,
94
+ tenantId: context.tenantId,
95
+ connectionId: context.connectionId ?? "unknown",
96
+ userId: readString(item, ["user_id", "userId", "athlete_id"]),
97
+ providerKey: context.providerKey,
98
+ activityType: readString(item, ["activity_type", "type", "sport_type", "sport"]) ?? fallbackType,
99
+ startedAt: readIsoDate(item, [
100
+ "started_at",
101
+ "start_time",
102
+ "start_date",
103
+ "created_at"
104
+ ]),
105
+ endedAt: readIsoDate(item, ["ended_at", "end_time"]),
106
+ durationSeconds: readNumber(item, [
107
+ "duration_seconds",
108
+ "duration",
109
+ "elapsed_time"
110
+ ]),
111
+ distanceMeters: readNumber(item, ["distance_meters", "distance"]),
112
+ caloriesKcal: readNumber(item, [
113
+ "calories_kcal",
114
+ "calories",
115
+ "active_kilocalories"
116
+ ]),
117
+ steps: readNumber(item, ["steps"])?.valueOf(),
118
+ metadata: item
119
+ };
120
+ }
121
+ function toHealthWorkout(item, context, fallbackType = "workout") {
122
+ const activity = toHealthActivity(item, context, fallbackType);
123
+ return {
124
+ id: activity.id,
125
+ externalId: activity.externalId,
126
+ tenantId: activity.tenantId,
127
+ connectionId: activity.connectionId,
128
+ userId: activity.userId,
129
+ providerKey: activity.providerKey,
130
+ workoutType: readString(item, [
131
+ "workout_type",
132
+ "sport_type",
133
+ "type",
134
+ "activity_type"
135
+ ]) ?? fallbackType,
136
+ startedAt: activity.startedAt,
137
+ endedAt: activity.endedAt,
138
+ durationSeconds: activity.durationSeconds,
139
+ distanceMeters: activity.distanceMeters,
140
+ caloriesKcal: activity.caloriesKcal,
141
+ averageHeartRateBpm: readNumber(item, [
142
+ "average_heart_rate",
143
+ "avg_hr",
144
+ "average_heart_rate_bpm"
145
+ ]),
146
+ maxHeartRateBpm: readNumber(item, [
147
+ "max_heart_rate",
148
+ "max_hr",
149
+ "max_heart_rate_bpm"
150
+ ]),
151
+ metadata: item
152
+ };
153
+ }
154
+ function toHealthSleep(item, context) {
155
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:sleep`;
156
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:sleep:${externalId}`;
157
+ const startedAt = readIsoDate(item, ["started_at", "start_time", "bedtime_start", "start"]) ?? new Date(0).toISOString();
158
+ const endedAt = readIsoDate(item, ["ended_at", "end_time", "bedtime_end", "end"]) ?? startedAt;
159
+ return {
160
+ id,
161
+ externalId,
162
+ tenantId: context.tenantId,
163
+ connectionId: context.connectionId ?? "unknown",
164
+ userId: readString(item, ["user_id", "userId"]),
165
+ providerKey: context.providerKey,
166
+ startedAt,
167
+ endedAt,
168
+ durationSeconds: readNumber(item, [
169
+ "duration_seconds",
170
+ "duration",
171
+ "total_sleep_duration"
172
+ ]),
173
+ deepSleepSeconds: readNumber(item, [
174
+ "deep_sleep_seconds",
175
+ "deep_sleep_duration"
176
+ ]),
177
+ lightSleepSeconds: readNumber(item, [
178
+ "light_sleep_seconds",
179
+ "light_sleep_duration"
180
+ ]),
181
+ remSleepSeconds: readNumber(item, [
182
+ "rem_sleep_seconds",
183
+ "rem_sleep_duration"
184
+ ]),
185
+ awakeSeconds: readNumber(item, ["awake_seconds", "awake_time"]),
186
+ sleepScore: readNumber(item, ["sleep_score", "score"]),
187
+ metadata: item
188
+ };
189
+ }
190
+ function toHealthBiometric(item, context, metricTypeFallback = "metric") {
191
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:biometric`;
192
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:biometric:${externalId}`;
193
+ return {
194
+ id,
195
+ externalId,
196
+ tenantId: context.tenantId,
197
+ connectionId: context.connectionId ?? "unknown",
198
+ userId: readString(item, ["user_id", "userId"]),
199
+ providerKey: context.providerKey,
200
+ metricType: readString(item, ["metric_type", "metric", "type", "name"]) ?? metricTypeFallback,
201
+ value: readNumber(item, ["value", "score", "measurement"]) ?? 0,
202
+ unit: readString(item, ["unit"]),
203
+ measuredAt: readIsoDate(item, ["measured_at", "timestamp", "created_at"]) ?? new Date().toISOString(),
204
+ metadata: item
205
+ };
206
+ }
207
+ function toHealthNutrition(item, context) {
208
+ const externalId = readString(item, ["external_id", "externalId", "uuid", "id"]) ?? `${context.providerKey}:nutrition`;
209
+ const id = readString(item, ["id", "uuid"]) ?? `${context.providerKey}:nutrition:${externalId}`;
210
+ return {
211
+ id,
212
+ externalId,
213
+ tenantId: context.tenantId,
214
+ connectionId: context.connectionId ?? "unknown",
215
+ userId: readString(item, ["user_id", "userId"]),
216
+ providerKey: context.providerKey,
217
+ loggedAt: readIsoDate(item, ["logged_at", "created_at", "date", "timestamp"]) ?? new Date().toISOString(),
218
+ caloriesKcal: readNumber(item, ["calories_kcal", "calories"]),
219
+ proteinGrams: readNumber(item, ["protein_grams", "protein"]),
220
+ carbsGrams: readNumber(item, ["carbs_grams", "carbs"]),
221
+ fatGrams: readNumber(item, ["fat_grams", "fat"]),
222
+ fiberGrams: readNumber(item, ["fiber_grams", "fiber"]),
223
+ hydrationMl: readNumber(item, ["hydration_ml", "water_ml", "water"]),
224
+ metadata: item
225
+ };
226
+ }
227
+ function toHealthConnectionStatus(payload, params, source) {
228
+ const record = asRecord(payload);
229
+ const rawStatus = readString(record, ["status", "connection_status", "health"]) ?? "healthy";
230
+ return {
231
+ tenantId: params.tenantId,
232
+ connectionId: params.connectionId,
233
+ status: rawStatus === "healthy" || rawStatus === "degraded" || rawStatus === "error" || rawStatus === "disconnected" ? rawStatus : "healthy",
234
+ source,
235
+ lastCheckedAt: readIsoDate(record, ["last_checked_at", "lastCheckedAt"]) ?? new Date().toISOString(),
236
+ errorCode: readString(record, ["error_code", "errorCode"]),
237
+ errorMessage: readString(record, ["error_message", "errorMessage"]),
238
+ metadata: asRecord(record?.metadata)
239
+ };
240
+ }
241
+ function toHealthWebhookEvent(payload, providerKey, verified) {
242
+ const record = asRecord(payload);
243
+ const entityType = readString(record, ["entity_type", "entityType", "type"]);
244
+ const normalizedEntityType = entityType === "activity" || entityType === "workout" || entityType === "sleep" || entityType === "biometric" || entityType === "nutrition" ? entityType : undefined;
245
+ return {
246
+ providerKey,
247
+ eventType: readString(record, ["event_type", "eventType", "event"]),
248
+ externalEntityId: readString(record, [
249
+ "external_entity_id",
250
+ "externalEntityId",
251
+ "entity_id",
252
+ "entityId",
253
+ "id"
254
+ ]),
255
+ entityType: normalizedEntityType,
256
+ receivedAt: new Date().toISOString(),
257
+ verified,
258
+ payload,
259
+ metadata: asRecord(record?.metadata)
260
+ };
261
+ }
262
+ function readIsoDate(record, keys) {
263
+ const value = readString(record, keys);
264
+ if (!value)
265
+ return;
266
+ const parsed = new Date(value);
267
+ if (Number.isNaN(parsed.getTime()))
268
+ return;
269
+ return parsed.toISOString();
270
+ }
271
+
1
272
  // src/impls/health/base-health-provider.ts
273
+ class HealthProviderCapabilityError extends Error {
274
+ code = "NOT_SUPPORTED";
275
+ constructor(message) {
276
+ super(message);
277
+ this.name = "HealthProviderCapabilityError";
278
+ }
279
+ }
280
+
2
281
  class BaseHealthProvider {
3
282
  providerKey;
4
283
  transport;
@@ -6,146 +285,191 @@ class BaseHealthProvider {
6
285
  mcpUrl;
7
286
  apiKey;
8
287
  accessToken;
288
+ refreshToken;
9
289
  mcpAccessToken;
10
290
  webhookSecret;
291
+ webhookSignatureHeader;
292
+ route;
293
+ aggregatorKey;
294
+ oauth;
11
295
  fetchFn;
12
296
  mcpRequestId = 0;
13
297
  constructor(options) {
14
298
  this.providerKey = options.providerKey;
15
299
  this.transport = options.transport;
16
- this.apiBaseUrl = options.apiBaseUrl ?? "https://api.example-health.local";
300
+ this.apiBaseUrl = options.apiBaseUrl;
17
301
  this.mcpUrl = options.mcpUrl;
18
302
  this.apiKey = options.apiKey;
19
303
  this.accessToken = options.accessToken;
304
+ this.refreshToken = options.oauth?.refreshToken;
20
305
  this.mcpAccessToken = options.mcpAccessToken;
21
306
  this.webhookSecret = options.webhookSecret;
307
+ this.webhookSignatureHeader = options.webhookSignatureHeader ?? "x-webhook-signature";
308
+ this.route = options.route ?? "primary";
309
+ this.aggregatorKey = options.aggregatorKey;
310
+ this.oauth = options.oauth ?? {};
22
311
  this.fetchFn = options.fetchFn ?? fetch;
23
312
  }
24
- async listActivities(params) {
25
- const result = await this.fetchList("activities", params);
26
- return {
27
- activities: result.items,
28
- nextCursor: result.nextCursor,
29
- hasMore: result.hasMore,
30
- source: this.currentSource()
31
- };
313
+ async listActivities(_params) {
314
+ throw this.unsupported("activities");
315
+ }
316
+ async listWorkouts(_params) {
317
+ throw this.unsupported("workouts");
318
+ }
319
+ async listSleep(_params) {
320
+ throw this.unsupported("sleep");
321
+ }
322
+ async listBiometrics(_params) {
323
+ throw this.unsupported("biometrics");
324
+ }
325
+ async listNutrition(_params) {
326
+ throw this.unsupported("nutrition");
327
+ }
328
+ async getConnectionStatus(params) {
329
+ return this.fetchConnectionStatus(params, {
330
+ mcpTool: `${this.providerSlug()}_connection_status`
331
+ });
332
+ }
333
+ async syncActivities(params) {
334
+ return this.syncFromList(() => this.listActivities(params));
32
335
  }
33
- async listWorkouts(params) {
34
- const result = await this.fetchList("workouts", params);
336
+ async syncWorkouts(params) {
337
+ return this.syncFromList(() => this.listWorkouts(params));
338
+ }
339
+ async syncSleep(params) {
340
+ return this.syncFromList(() => this.listSleep(params));
341
+ }
342
+ async syncBiometrics(params) {
343
+ return this.syncFromList(() => this.listBiometrics(params));
344
+ }
345
+ async syncNutrition(params) {
346
+ return this.syncFromList(() => this.listNutrition(params));
347
+ }
348
+ async parseWebhook(request) {
349
+ const payload = request.parsedBody ?? safeJsonParse(request.rawBody);
350
+ const verified = await this.verifyWebhook(request);
351
+ return toHealthWebhookEvent(payload, this.providerKey, verified);
352
+ }
353
+ async verifyWebhook(request) {
354
+ if (!this.webhookSecret)
355
+ return true;
356
+ const signature = readHeader(request.headers, this.webhookSignatureHeader);
357
+ return signature === this.webhookSecret;
358
+ }
359
+ async fetchActivities(params, config) {
360
+ const response = await this.fetchList(params, config);
35
361
  return {
36
- workouts: result.items,
37
- nextCursor: result.nextCursor,
38
- hasMore: result.hasMore,
362
+ activities: response.items,
363
+ nextCursor: response.nextCursor,
364
+ hasMore: response.hasMore,
39
365
  source: this.currentSource()
40
366
  };
41
367
  }
42
- async listSleep(params) {
43
- const result = await this.fetchList("sleep", params);
368
+ async fetchWorkouts(params, config) {
369
+ const response = await this.fetchList(params, config);
44
370
  return {
45
- sleep: result.items,
46
- nextCursor: result.nextCursor,
47
- hasMore: result.hasMore,
371
+ workouts: response.items,
372
+ nextCursor: response.nextCursor,
373
+ hasMore: response.hasMore,
48
374
  source: this.currentSource()
49
375
  };
50
376
  }
51
- async listBiometrics(params) {
52
- const result = await this.fetchList("biometrics", params);
377
+ async fetchSleep(params, config) {
378
+ const response = await this.fetchList(params, config);
53
379
  return {
54
- biometrics: result.items,
55
- nextCursor: result.nextCursor,
56
- hasMore: result.hasMore,
380
+ sleep: response.items,
381
+ nextCursor: response.nextCursor,
382
+ hasMore: response.hasMore,
57
383
  source: this.currentSource()
58
384
  };
59
385
  }
60
- async listNutrition(params) {
61
- const result = await this.fetchList("nutrition", params);
386
+ async fetchBiometrics(params, config) {
387
+ const response = await this.fetchList(params, config);
62
388
  return {
63
- nutrition: result.items,
64
- nextCursor: result.nextCursor,
65
- hasMore: result.hasMore,
389
+ biometrics: response.items,
390
+ nextCursor: response.nextCursor,
391
+ hasMore: response.hasMore,
66
392
  source: this.currentSource()
67
393
  };
68
394
  }
69
- async getConnectionStatus(params) {
70
- const payload = await this.fetchRecord("connection/status", params);
71
- const status = readString(payload, "status") ?? "healthy";
395
+ async fetchNutrition(params, config) {
396
+ const response = await this.fetchList(params, config);
72
397
  return {
73
- tenantId: params.tenantId,
74
- connectionId: params.connectionId,
75
- status: status === "healthy" || status === "degraded" || status === "error" || status === "disconnected" ? status : "healthy",
76
- source: this.currentSource(),
77
- lastCheckedAt: readString(payload, "lastCheckedAt") ?? new Date().toISOString(),
78
- errorCode: readString(payload, "errorCode"),
79
- errorMessage: readString(payload, "errorMessage"),
80
- metadata: asRecord(payload.metadata)
398
+ nutrition: response.items,
399
+ nextCursor: response.nextCursor,
400
+ hasMore: response.hasMore,
401
+ source: this.currentSource()
81
402
  };
82
403
  }
83
- async syncActivities(params) {
84
- return this.sync("activities", params);
85
- }
86
- async syncWorkouts(params) {
87
- return this.sync("workouts", params);
404
+ async fetchConnectionStatus(params, config) {
405
+ const payload = await this.fetchPayload(config, params);
406
+ return toHealthConnectionStatus(payload, params, this.currentSource());
88
407
  }
89
- async syncSleep(params) {
90
- return this.sync("sleep", params);
91
- }
92
- async syncBiometrics(params) {
93
- return this.sync("biometrics", params);
94
- }
95
- async syncNutrition(params) {
96
- return this.sync("nutrition", params);
97
- }
98
- async parseWebhook(request) {
99
- const payload = request.parsedBody ?? safeJsonParse(request.rawBody);
100
- const body = asRecord(payload);
408
+ currentSource() {
101
409
  return {
102
410
  providerKey: this.providerKey,
103
- eventType: readString(body, "eventType") ?? readString(body, "event"),
104
- externalEntityId: readString(body, "externalEntityId") ?? readString(body, "entityId"),
105
- entityType: normalizeEntityType(readString(body, "entityType") ?? readString(body, "type")),
106
- receivedAt: new Date().toISOString(),
107
- verified: await this.verifyWebhook(request),
108
- payload
411
+ transport: this.transport,
412
+ route: this.route,
413
+ aggregatorKey: this.aggregatorKey
109
414
  };
110
415
  }
111
- async verifyWebhook(request) {
112
- if (!this.webhookSecret) {
113
- return true;
114
- }
115
- const signature = readHeader(request.headers, "x-webhook-signature");
116
- return signature === this.webhookSecret;
416
+ providerSlug() {
417
+ return this.providerKey.replace("health.", "").replace(/-/g, "_");
117
418
  }
118
- async fetchList(resource, params) {
119
- const payload = await this.fetchRecord(resource, params);
120
- const items = asArray(payload.items) ?? asArray(payload[resource]) ?? asArray(payload.records) ?? [];
419
+ unsupported(capability) {
420
+ return new HealthProviderCapabilityError(`${this.providerKey} does not support ${capability}`);
421
+ }
422
+ async syncFromList(executor) {
423
+ const result = await executor();
424
+ const records = countResultRecords(result);
121
425
  return {
122
- items,
123
- nextCursor: readString(payload, "nextCursor") ?? readString(payload, "cursor"),
124
- hasMore: readBoolean(payload, "hasMore")
426
+ synced: records,
427
+ failed: 0,
428
+ nextCursor: undefined,
429
+ source: result.source
125
430
  };
126
431
  }
127
- async sync(resource, params) {
128
- const payload = await this.fetchRecord(`sync/${resource}`, params, "POST");
432
+ async fetchList(params, config) {
433
+ const payload = await this.fetchPayload(config, params);
434
+ const items = extractList(payload, config.listKeys).map((item) => config.mapItem(item, params)).filter((item) => Boolean(item));
435
+ const pagination = extractPagination(payload);
129
436
  return {
130
- synced: readNumber(payload, "synced") ?? 0,
131
- failed: readNumber(payload, "failed") ?? 0,
132
- nextCursor: readString(payload, "nextCursor"),
133
- errors: asArray(payload.errors)?.map((item) => String(item)),
134
- source: this.currentSource()
437
+ items,
438
+ nextCursor: pagination.nextCursor,
439
+ hasMore: pagination.hasMore
135
440
  };
136
441
  }
137
- async fetchRecord(resource, params, method = "GET") {
138
- if (this.transport.endsWith("mcp")) {
139
- return this.callMcpTool(resource, params);
442
+ async fetchPayload(config, params) {
443
+ const method = config.method ?? "GET";
444
+ const query = config.buildQuery?.(params);
445
+ const body = config.buildBody?.(params);
446
+ if (this.isMcpTransport()) {
447
+ return this.callMcpTool(config.mcpTool, {
448
+ ...query ?? {},
449
+ ...body ?? {}
450
+ });
451
+ }
452
+ if (!config.apiPath || !this.apiBaseUrl) {
453
+ throw new Error(`${this.providerKey} transport is missing an API path.`);
140
454
  }
141
- const url = new URL(`${this.apiBaseUrl.replace(/\/$/, "")}/${resource}`);
142
- if (method === "GET") {
143
- for (const [key, value] of Object.entries(params)) {
455
+ if (method === "POST") {
456
+ return this.requestApi(config.apiPath, "POST", undefined, body);
457
+ }
458
+ return this.requestApi(config.apiPath, "GET", query, undefined);
459
+ }
460
+ isMcpTransport() {
461
+ return this.transport.endsWith("mcp") || this.transport === "unofficial";
462
+ }
463
+ async requestApi(path, method, query, body) {
464
+ const url = new URL(path, ensureTrailingSlash(this.apiBaseUrl ?? ""));
465
+ if (query) {
466
+ for (const [key, value] of Object.entries(query)) {
144
467
  if (value == null)
145
468
  continue;
146
469
  if (Array.isArray(value)) {
147
- value.forEach((item) => {
148
- url.searchParams.append(key, String(item));
470
+ value.forEach((entry) => {
471
+ if (entry != null)
472
+ url.searchParams.append(key, String(entry));
149
473
  });
150
474
  continue;
151
475
  }
@@ -154,22 +478,22 @@ class BaseHealthProvider {
154
478
  }
155
479
  const response = await this.fetchFn(url, {
156
480
  method,
157
- headers: {
158
- "Content-Type": "application/json",
159
- ...this.accessToken || this.apiKey ? { Authorization: `Bearer ${this.accessToken ?? this.apiKey}` } : {}
160
- },
161
- body: method === "POST" ? JSON.stringify(params) : undefined
481
+ headers: this.authorizationHeaders(),
482
+ body: method === "POST" ? JSON.stringify(body ?? {}) : undefined
162
483
  });
163
- if (!response.ok) {
164
- const errorBody = await safeResponseText(response);
165
- throw new Error(`${this.providerKey} ${resource} failed (${response.status}): ${errorBody}`);
484
+ if (response.status === 401 && await this.refreshAccessToken()) {
485
+ const retryResponse = await this.fetchFn(url, {
486
+ method,
487
+ headers: this.authorizationHeaders(),
488
+ body: method === "POST" ? JSON.stringify(body ?? {}) : undefined
489
+ });
490
+ return this.readResponsePayload(retryResponse, path);
166
491
  }
167
- const data = await response.json();
168
- return asRecord(data) ?? {};
492
+ return this.readResponsePayload(response, path);
169
493
  }
170
- async callMcpTool(resource, params) {
494
+ async callMcpTool(toolName, args) {
171
495
  if (!this.mcpUrl) {
172
- return {};
496
+ throw new Error(`${this.providerKey} MCP URL is not configured.`);
173
497
  }
174
498
  const response = await this.fetchFn(this.mcpUrl, {
175
499
  method: "POST",
@@ -182,78 +506,103 @@ class BaseHealthProvider {
182
506
  id: ++this.mcpRequestId,
183
507
  method: "tools/call",
184
508
  params: {
185
- name: `${this.providerKey.replace("health.", "")}_${resource.replace(/\//g, "_")}`,
186
- arguments: params
509
+ name: toolName,
510
+ arguments: args
187
511
  }
188
512
  })
189
513
  });
190
- if (!response.ok) {
191
- const errorBody = await safeResponseText(response);
192
- throw new Error(`${this.providerKey} MCP ${resource} failed (${response.status}): ${errorBody}`);
514
+ const payload = await this.readResponsePayload(response, toolName);
515
+ const rpcEnvelope = asRecord(payload);
516
+ if (!rpcEnvelope)
517
+ return payload;
518
+ const rpcResult = asRecord(rpcEnvelope.result);
519
+ if (rpcResult) {
520
+ return rpcResult.structuredContent ?? rpcResult.data ?? rpcResult;
193
521
  }
194
- const rpcPayload = await response.json();
195
- const rpc = asRecord(rpcPayload);
196
- const result = asRecord(rpc?.result) ?? {};
197
- const structured = asRecord(result.structuredContent);
198
- if (structured)
199
- return structured;
200
- const data = asRecord(result.data);
201
- if (data)
202
- return data;
203
- return result;
522
+ return rpcEnvelope.structuredContent ?? rpcEnvelope.data ?? rpcEnvelope;
204
523
  }
205
- currentSource() {
524
+ authorizationHeaders() {
525
+ const token = this.accessToken ?? this.apiKey;
206
526
  return {
207
- providerKey: this.providerKey,
208
- transport: this.transport,
209
- route: "primary"
527
+ "Content-Type": "application/json",
528
+ ...token ? { Authorization: `Bearer ${token}` } : {}
210
529
  };
211
530
  }
212
- }
213
- function safeJsonParse(raw) {
214
- try {
215
- return JSON.parse(raw);
216
- } catch {
217
- return { rawBody: raw };
531
+ async refreshAccessToken() {
532
+ if (!this.oauth.tokenUrl || !this.refreshToken) {
533
+ return false;
534
+ }
535
+ const tokenUrl = new URL(this.oauth.tokenUrl);
536
+ const body = new URLSearchParams({
537
+ grant_type: "refresh_token",
538
+ refresh_token: this.refreshToken,
539
+ ...this.oauth.clientId ? { client_id: this.oauth.clientId } : {},
540
+ ...this.oauth.clientSecret ? { client_secret: this.oauth.clientSecret } : {}
541
+ });
542
+ const response = await this.fetchFn(tokenUrl, {
543
+ method: "POST",
544
+ headers: {
545
+ "Content-Type": "application/x-www-form-urlencoded"
546
+ },
547
+ body: body.toString()
548
+ });
549
+ if (!response.ok) {
550
+ return false;
551
+ }
552
+ const payload = await response.json();
553
+ this.accessToken = payload.access_token;
554
+ this.refreshToken = payload.refresh_token ?? this.refreshToken;
555
+ if (typeof payload.expires_in === "number") {
556
+ this.oauth.tokenExpiresAt = new Date(Date.now() + payload.expires_in * 1000).toISOString();
557
+ }
558
+ return Boolean(this.accessToken);
559
+ }
560
+ async readResponsePayload(response, context) {
561
+ if (!response.ok) {
562
+ const message = await safeReadText(response);
563
+ throw new Error(`${this.providerKey} request ${context} failed (${response.status}): ${message}`);
564
+ }
565
+ if (response.status === 204) {
566
+ return {};
567
+ }
568
+ return response.json();
218
569
  }
219
570
  }
220
571
  function readHeader(headers, key) {
221
- const match = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === key.toLowerCase());
222
- if (!match)
572
+ const target = key.toLowerCase();
573
+ const entry = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === target);
574
+ if (!entry)
223
575
  return;
224
- const value = match[1];
576
+ const value = entry[1];
225
577
  return Array.isArray(value) ? value[0] : value;
226
578
  }
227
- function normalizeEntityType(value) {
228
- if (!value)
229
- return;
230
- if (value === "activity" || value === "workout" || value === "sleep" || value === "biometric" || value === "nutrition") {
231
- return value;
232
- }
233
- return;
234
- }
235
- function asRecord(value) {
236
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
237
- return;
579
+ function countResultRecords(result) {
580
+ const listKeys = [
581
+ "activities",
582
+ "workouts",
583
+ "sleep",
584
+ "biometrics",
585
+ "nutrition"
586
+ ];
587
+ for (const key of listKeys) {
588
+ const value = result[key];
589
+ if (Array.isArray(value)) {
590
+ return value.length;
591
+ }
238
592
  }
239
- return value;
240
- }
241
- function asArray(value) {
242
- return Array.isArray(value) ? value : undefined;
243
- }
244
- function readString(record, key) {
245
- const value = record?.[key];
246
- return typeof value === "string" ? value : undefined;
593
+ return 0;
247
594
  }
248
- function readBoolean(record, key) {
249
- const value = record?.[key];
250
- return typeof value === "boolean" ? value : undefined;
595
+ function ensureTrailingSlash(value) {
596
+ return value.endsWith("/") ? value : `${value}/`;
251
597
  }
252
- function readNumber(record, key) {
253
- const value = record?.[key];
254
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
598
+ function safeJsonParse(raw) {
599
+ try {
600
+ return JSON.parse(raw);
601
+ } catch {
602
+ return { rawBody: raw };
603
+ }
255
604
  }
256
- async function safeResponseText(response) {
605
+ async function safeReadText(response) {
257
606
  try {
258
607
  return await response.text();
259
608
  } catch {
@@ -261,5 +610,6 @@ async function safeResponseText(response) {
261
610
  }
262
611
  }
263
612
  export {
613
+ HealthProviderCapabilityError,
264
614
  BaseHealthProvider
265
615
  };