@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.
- package/README.md +7 -1
- package/dist/impls/async-event-queue.d.ts +8 -0
- package/dist/impls/async-event-queue.js +47 -0
- package/dist/impls/health/base-health-provider.d.ts +64 -13
- package/dist/impls/health/base-health-provider.js +506 -156
- package/dist/impls/health/hybrid-health-providers.d.ts +34 -0
- package/dist/impls/health/hybrid-health-providers.js +1088 -0
- package/dist/impls/health/official-health-providers.d.ts +78 -0
- package/dist/impls/health/official-health-providers.js +968 -0
- package/dist/impls/health/provider-normalizers.d.ts +28 -0
- package/dist/impls/health/provider-normalizers.js +287 -0
- package/dist/impls/health/providers.d.ts +2 -39
- package/dist/impls/health/providers.js +895 -184
- package/dist/impls/health-provider-factory.js +1009 -196
- package/dist/impls/index.d.ts +6 -0
- package/dist/impls/index.js +1950 -278
- package/dist/impls/messaging-github.d.ts +17 -0
- package/dist/impls/messaging-github.js +110 -0
- package/dist/impls/messaging-slack.d.ts +14 -0
- package/dist/impls/messaging-slack.js +80 -0
- package/dist/impls/messaging-whatsapp-meta.d.ts +13 -0
- package/dist/impls/messaging-whatsapp-meta.js +52 -0
- package/dist/impls/messaging-whatsapp-twilio.d.ts +13 -0
- package/dist/impls/messaging-whatsapp-twilio.js +82 -0
- package/dist/impls/mistral-conversational.d.ts +23 -0
- package/dist/impls/mistral-conversational.js +476 -0
- package/dist/impls/mistral-conversational.session.d.ts +32 -0
- package/dist/impls/mistral-conversational.session.js +206 -0
- package/dist/impls/mistral-stt.d.ts +17 -0
- package/dist/impls/mistral-stt.js +167 -0
- package/dist/impls/provider-factory.d.ts +5 -1
- package/dist/impls/provider-factory.js +1943 -277
- package/dist/impls/stripe-payments.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1953 -278
- package/dist/messaging.d.ts +1 -0
- package/dist/messaging.js +3 -0
- package/dist/node/impls/async-event-queue.js +46 -0
- package/dist/node/impls/health/base-health-provider.js +506 -156
- package/dist/node/impls/health/hybrid-health-providers.js +1087 -0
- package/dist/node/impls/health/official-health-providers.js +967 -0
- package/dist/node/impls/health/provider-normalizers.js +286 -0
- package/dist/node/impls/health/providers.js +895 -184
- package/dist/node/impls/health-provider-factory.js +1009 -196
- package/dist/node/impls/index.js +1950 -278
- package/dist/node/impls/messaging-github.js +109 -0
- package/dist/node/impls/messaging-slack.js +79 -0
- package/dist/node/impls/messaging-whatsapp-meta.js +51 -0
- package/dist/node/impls/messaging-whatsapp-twilio.js +81 -0
- package/dist/node/impls/mistral-conversational.js +475 -0
- package/dist/node/impls/mistral-conversational.session.js +205 -0
- package/dist/node/impls/mistral-stt.js +166 -0
- package/dist/node/impls/provider-factory.js +1943 -277
- package/dist/node/impls/stripe-payments.js +1 -1
- package/dist/node/index.js +1953 -278
- package/dist/node/messaging.js +2 -0
- 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
|
|
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(
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
|
34
|
-
|
|
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
|
-
|
|
37
|
-
nextCursor:
|
|
38
|
-
hasMore:
|
|
362
|
+
activities: response.items,
|
|
363
|
+
nextCursor: response.nextCursor,
|
|
364
|
+
hasMore: response.hasMore,
|
|
39
365
|
source: this.currentSource()
|
|
40
366
|
};
|
|
41
367
|
}
|
|
42
|
-
async
|
|
43
|
-
const
|
|
368
|
+
async fetchWorkouts(params, config) {
|
|
369
|
+
const response = await this.fetchList(params, config);
|
|
44
370
|
return {
|
|
45
|
-
|
|
46
|
-
nextCursor:
|
|
47
|
-
hasMore:
|
|
371
|
+
workouts: response.items,
|
|
372
|
+
nextCursor: response.nextCursor,
|
|
373
|
+
hasMore: response.hasMore,
|
|
48
374
|
source: this.currentSource()
|
|
49
375
|
};
|
|
50
376
|
}
|
|
51
|
-
async
|
|
52
|
-
const
|
|
377
|
+
async fetchSleep(params, config) {
|
|
378
|
+
const response = await this.fetchList(params, config);
|
|
53
379
|
return {
|
|
54
|
-
|
|
55
|
-
nextCursor:
|
|
56
|
-
hasMore:
|
|
380
|
+
sleep: response.items,
|
|
381
|
+
nextCursor: response.nextCursor,
|
|
382
|
+
hasMore: response.hasMore,
|
|
57
383
|
source: this.currentSource()
|
|
58
384
|
};
|
|
59
385
|
}
|
|
60
|
-
async
|
|
61
|
-
const
|
|
386
|
+
async fetchBiometrics(params, config) {
|
|
387
|
+
const response = await this.fetchList(params, config);
|
|
62
388
|
return {
|
|
63
|
-
|
|
64
|
-
nextCursor:
|
|
65
|
-
hasMore:
|
|
389
|
+
biometrics: response.items,
|
|
390
|
+
nextCursor: response.nextCursor,
|
|
391
|
+
hasMore: response.hasMore,
|
|
66
392
|
source: this.currentSource()
|
|
67
393
|
};
|
|
68
394
|
}
|
|
69
|
-
async
|
|
70
|
-
const
|
|
71
|
-
const status = readString(payload, "status") ?? "healthy";
|
|
395
|
+
async fetchNutrition(params, config) {
|
|
396
|
+
const response = await this.fetchList(params, config);
|
|
72
397
|
return {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
|
84
|
-
|
|
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
|
-
|
|
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
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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
|
-
|
|
112
|
-
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
426
|
+
synced: records,
|
|
427
|
+
failed: 0,
|
|
428
|
+
nextCursor: undefined,
|
|
429
|
+
source: result.source
|
|
125
430
|
};
|
|
126
431
|
}
|
|
127
|
-
async
|
|
128
|
-
const payload = await this.
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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((
|
|
148
|
-
|
|
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
|
-
|
|
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 (
|
|
164
|
-
const
|
|
165
|
-
|
|
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
|
-
|
|
168
|
-
return asRecord(data) ?? {};
|
|
492
|
+
return this.readResponsePayload(response, path);
|
|
169
493
|
}
|
|
170
|
-
async callMcpTool(
|
|
494
|
+
async callMcpTool(toolName, args) {
|
|
171
495
|
if (!this.mcpUrl) {
|
|
172
|
-
|
|
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:
|
|
186
|
-
arguments:
|
|
509
|
+
name: toolName,
|
|
510
|
+
arguments: args
|
|
187
511
|
}
|
|
188
512
|
})
|
|
189
513
|
});
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
-
|
|
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
|
-
|
|
524
|
+
authorizationHeaders() {
|
|
525
|
+
const token = this.accessToken ?? this.apiKey;
|
|
206
526
|
return {
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
route: "primary"
|
|
527
|
+
"Content-Type": "application/json",
|
|
528
|
+
...token ? { Authorization: `Bearer ${token}` } : {}
|
|
210
529
|
};
|
|
211
530
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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
|
|
222
|
-
|
|
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 =
|
|
576
|
+
const value = entry[1];
|
|
225
577
|
return Array.isArray(value) ? value[0] : value;
|
|
226
578
|
}
|
|
227
|
-
function
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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
|
|
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
|
|
249
|
-
|
|
250
|
-
return typeof value === "boolean" ? value : undefined;
|
|
595
|
+
function ensureTrailingSlash(value) {
|
|
596
|
+
return value.endsWith("/") ? value : `${value}/`;
|
|
251
597
|
}
|
|
252
|
-
function
|
|
253
|
-
|
|
254
|
-
|
|
598
|
+
function safeJsonParse(raw) {
|
|
599
|
+
try {
|
|
600
|
+
return JSON.parse(raw);
|
|
601
|
+
} catch {
|
|
602
|
+
return { rawBody: raw };
|
|
603
|
+
}
|
|
255
604
|
}
|
|
256
|
-
async function
|
|
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
|
};
|