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