@contractspec/integration.providers-impls 2.8.0 → 2.10.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.
@@ -1464,6 +1464,498 @@ async function safeReadError3(response) {
1464
1464
  }
1465
1465
  }
1466
1466
 
1467
+ // src/impls/health/base-health-provider.ts
1468
+ class BaseHealthProvider {
1469
+ providerKey;
1470
+ transport;
1471
+ apiBaseUrl;
1472
+ mcpUrl;
1473
+ apiKey;
1474
+ accessToken;
1475
+ mcpAccessToken;
1476
+ webhookSecret;
1477
+ fetchFn;
1478
+ mcpRequestId = 0;
1479
+ constructor(options) {
1480
+ this.providerKey = options.providerKey;
1481
+ this.transport = options.transport;
1482
+ this.apiBaseUrl = options.apiBaseUrl ?? "https://api.example-health.local";
1483
+ this.mcpUrl = options.mcpUrl;
1484
+ this.apiKey = options.apiKey;
1485
+ this.accessToken = options.accessToken;
1486
+ this.mcpAccessToken = options.mcpAccessToken;
1487
+ this.webhookSecret = options.webhookSecret;
1488
+ this.fetchFn = options.fetchFn ?? fetch;
1489
+ }
1490
+ async listActivities(params) {
1491
+ const result = await this.fetchList("activities", params);
1492
+ return {
1493
+ activities: result.items,
1494
+ nextCursor: result.nextCursor,
1495
+ hasMore: result.hasMore,
1496
+ source: this.currentSource()
1497
+ };
1498
+ }
1499
+ async listWorkouts(params) {
1500
+ const result = await this.fetchList("workouts", params);
1501
+ return {
1502
+ workouts: result.items,
1503
+ nextCursor: result.nextCursor,
1504
+ hasMore: result.hasMore,
1505
+ source: this.currentSource()
1506
+ };
1507
+ }
1508
+ async listSleep(params) {
1509
+ const result = await this.fetchList("sleep", params);
1510
+ return {
1511
+ sleep: result.items,
1512
+ nextCursor: result.nextCursor,
1513
+ hasMore: result.hasMore,
1514
+ source: this.currentSource()
1515
+ };
1516
+ }
1517
+ async listBiometrics(params) {
1518
+ const result = await this.fetchList("biometrics", params);
1519
+ return {
1520
+ biometrics: result.items,
1521
+ nextCursor: result.nextCursor,
1522
+ hasMore: result.hasMore,
1523
+ source: this.currentSource()
1524
+ };
1525
+ }
1526
+ async listNutrition(params) {
1527
+ const result = await this.fetchList("nutrition", params);
1528
+ return {
1529
+ nutrition: result.items,
1530
+ nextCursor: result.nextCursor,
1531
+ hasMore: result.hasMore,
1532
+ source: this.currentSource()
1533
+ };
1534
+ }
1535
+ async getConnectionStatus(params) {
1536
+ const payload = await this.fetchRecord("connection/status", params);
1537
+ const status = readString2(payload, "status") ?? "healthy";
1538
+ return {
1539
+ tenantId: params.tenantId,
1540
+ connectionId: params.connectionId,
1541
+ status: status === "healthy" || status === "degraded" || status === "error" || status === "disconnected" ? status : "healthy",
1542
+ source: this.currentSource(),
1543
+ lastCheckedAt: readString2(payload, "lastCheckedAt") ?? new Date().toISOString(),
1544
+ errorCode: readString2(payload, "errorCode"),
1545
+ errorMessage: readString2(payload, "errorMessage"),
1546
+ metadata: asRecord(payload.metadata)
1547
+ };
1548
+ }
1549
+ async syncActivities(params) {
1550
+ return this.sync("activities", params);
1551
+ }
1552
+ async syncWorkouts(params) {
1553
+ return this.sync("workouts", params);
1554
+ }
1555
+ async syncSleep(params) {
1556
+ return this.sync("sleep", params);
1557
+ }
1558
+ async syncBiometrics(params) {
1559
+ return this.sync("biometrics", params);
1560
+ }
1561
+ async syncNutrition(params) {
1562
+ return this.sync("nutrition", params);
1563
+ }
1564
+ async parseWebhook(request) {
1565
+ const payload = request.parsedBody ?? safeJsonParse(request.rawBody);
1566
+ const body = asRecord(payload);
1567
+ return {
1568
+ providerKey: this.providerKey,
1569
+ eventType: readString2(body, "eventType") ?? readString2(body, "event"),
1570
+ externalEntityId: readString2(body, "externalEntityId") ?? readString2(body, "entityId"),
1571
+ entityType: normalizeEntityType(readString2(body, "entityType") ?? readString2(body, "type")),
1572
+ receivedAt: new Date().toISOString(),
1573
+ verified: await this.verifyWebhook(request),
1574
+ payload
1575
+ };
1576
+ }
1577
+ async verifyWebhook(request) {
1578
+ if (!this.webhookSecret) {
1579
+ return true;
1580
+ }
1581
+ const signature = readHeader(request.headers, "x-webhook-signature");
1582
+ return signature === this.webhookSecret;
1583
+ }
1584
+ async fetchList(resource, params) {
1585
+ const payload = await this.fetchRecord(resource, params);
1586
+ const items = asArray2(payload.items) ?? asArray2(payload[resource]) ?? asArray2(payload.records) ?? [];
1587
+ return {
1588
+ items,
1589
+ nextCursor: readString2(payload, "nextCursor") ?? readString2(payload, "cursor"),
1590
+ hasMore: readBoolean2(payload, "hasMore")
1591
+ };
1592
+ }
1593
+ async sync(resource, params) {
1594
+ const payload = await this.fetchRecord(`sync/${resource}`, params, "POST");
1595
+ return {
1596
+ synced: readNumber(payload, "synced") ?? 0,
1597
+ failed: readNumber(payload, "failed") ?? 0,
1598
+ nextCursor: readString2(payload, "nextCursor"),
1599
+ errors: asArray2(payload.errors)?.map((item) => String(item)),
1600
+ source: this.currentSource()
1601
+ };
1602
+ }
1603
+ async fetchRecord(resource, params, method = "GET") {
1604
+ if (this.transport.endsWith("mcp")) {
1605
+ return this.callMcpTool(resource, params);
1606
+ }
1607
+ const url = new URL(`${this.apiBaseUrl.replace(/\/$/, "")}/${resource}`);
1608
+ if (method === "GET") {
1609
+ for (const [key, value] of Object.entries(params)) {
1610
+ if (value == null)
1611
+ continue;
1612
+ if (Array.isArray(value)) {
1613
+ value.forEach((item) => {
1614
+ url.searchParams.append(key, String(item));
1615
+ });
1616
+ continue;
1617
+ }
1618
+ url.searchParams.set(key, String(value));
1619
+ }
1620
+ }
1621
+ const response = await this.fetchFn(url, {
1622
+ method,
1623
+ headers: {
1624
+ "Content-Type": "application/json",
1625
+ ...this.accessToken || this.apiKey ? { Authorization: `Bearer ${this.accessToken ?? this.apiKey}` } : {}
1626
+ },
1627
+ body: method === "POST" ? JSON.stringify(params) : undefined
1628
+ });
1629
+ if (!response.ok) {
1630
+ const errorBody = await safeResponseText(response);
1631
+ throw new Error(`${this.providerKey} ${resource} failed (${response.status}): ${errorBody}`);
1632
+ }
1633
+ const data = await response.json();
1634
+ return asRecord(data) ?? {};
1635
+ }
1636
+ async callMcpTool(resource, params) {
1637
+ if (!this.mcpUrl) {
1638
+ return {};
1639
+ }
1640
+ const response = await this.fetchFn(this.mcpUrl, {
1641
+ method: "POST",
1642
+ headers: {
1643
+ "Content-Type": "application/json",
1644
+ ...this.mcpAccessToken ? { Authorization: `Bearer ${this.mcpAccessToken}` } : {}
1645
+ },
1646
+ body: JSON.stringify({
1647
+ jsonrpc: "2.0",
1648
+ id: ++this.mcpRequestId,
1649
+ method: "tools/call",
1650
+ params: {
1651
+ name: `${this.providerKey.replace("health.", "")}_${resource.replace(/\//g, "_")}`,
1652
+ arguments: params
1653
+ }
1654
+ })
1655
+ });
1656
+ if (!response.ok) {
1657
+ const errorBody = await safeResponseText(response);
1658
+ throw new Error(`${this.providerKey} MCP ${resource} failed (${response.status}): ${errorBody}`);
1659
+ }
1660
+ const rpcPayload = await response.json();
1661
+ const rpc = asRecord(rpcPayload);
1662
+ const result = asRecord(rpc?.result) ?? {};
1663
+ const structured = asRecord(result.structuredContent);
1664
+ if (structured)
1665
+ return structured;
1666
+ const data = asRecord(result.data);
1667
+ if (data)
1668
+ return data;
1669
+ return result;
1670
+ }
1671
+ currentSource() {
1672
+ return {
1673
+ providerKey: this.providerKey,
1674
+ transport: this.transport,
1675
+ route: "primary"
1676
+ };
1677
+ }
1678
+ }
1679
+ function safeJsonParse(raw) {
1680
+ try {
1681
+ return JSON.parse(raw);
1682
+ } catch {
1683
+ return { rawBody: raw };
1684
+ }
1685
+ }
1686
+ function readHeader(headers, key) {
1687
+ const match = Object.entries(headers).find(([headerKey]) => headerKey.toLowerCase() === key.toLowerCase());
1688
+ if (!match)
1689
+ return;
1690
+ const value = match[1];
1691
+ return Array.isArray(value) ? value[0] : value;
1692
+ }
1693
+ function normalizeEntityType(value) {
1694
+ if (!value)
1695
+ return;
1696
+ if (value === "activity" || value === "workout" || value === "sleep" || value === "biometric" || value === "nutrition") {
1697
+ return value;
1698
+ }
1699
+ return;
1700
+ }
1701
+ function asRecord(value) {
1702
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1703
+ return;
1704
+ }
1705
+ return value;
1706
+ }
1707
+ function asArray2(value) {
1708
+ return Array.isArray(value) ? value : undefined;
1709
+ }
1710
+ function readString2(record, key) {
1711
+ const value = record?.[key];
1712
+ return typeof value === "string" ? value : undefined;
1713
+ }
1714
+ function readBoolean2(record, key) {
1715
+ const value = record?.[key];
1716
+ return typeof value === "boolean" ? value : undefined;
1717
+ }
1718
+ function readNumber(record, key) {
1719
+ const value = record?.[key];
1720
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
1721
+ }
1722
+ async function safeResponseText(response) {
1723
+ try {
1724
+ return await response.text();
1725
+ } catch {
1726
+ return response.statusText;
1727
+ }
1728
+ }
1729
+
1730
+ // src/impls/health/providers.ts
1731
+ function createProviderOptions(options, fallbackTransport) {
1732
+ return {
1733
+ ...options,
1734
+ transport: options.transport ?? fallbackTransport
1735
+ };
1736
+ }
1737
+
1738
+ class OpenWearablesHealthProvider extends BaseHealthProvider {
1739
+ constructor(options) {
1740
+ super({
1741
+ providerKey: "health.openwearables",
1742
+ ...createProviderOptions(options, "aggregator-api")
1743
+ });
1744
+ }
1745
+ }
1746
+
1747
+ class WhoopHealthProvider extends BaseHealthProvider {
1748
+ constructor(options) {
1749
+ super({
1750
+ providerKey: "health.whoop",
1751
+ ...createProviderOptions(options, "official-api")
1752
+ });
1753
+ }
1754
+ }
1755
+
1756
+ class AppleHealthBridgeProvider extends BaseHealthProvider {
1757
+ constructor(options) {
1758
+ super({
1759
+ providerKey: "health.apple-health",
1760
+ ...createProviderOptions(options, "aggregator-api")
1761
+ });
1762
+ }
1763
+ }
1764
+
1765
+ class OuraHealthProvider extends BaseHealthProvider {
1766
+ constructor(options) {
1767
+ super({
1768
+ providerKey: "health.oura",
1769
+ ...createProviderOptions(options, "official-api")
1770
+ });
1771
+ }
1772
+ }
1773
+
1774
+ class StravaHealthProvider extends BaseHealthProvider {
1775
+ constructor(options) {
1776
+ super({
1777
+ providerKey: "health.strava",
1778
+ ...createProviderOptions(options, "official-api")
1779
+ });
1780
+ }
1781
+ }
1782
+
1783
+ class GarminHealthProvider extends BaseHealthProvider {
1784
+ constructor(options) {
1785
+ super({
1786
+ providerKey: "health.garmin",
1787
+ ...createProviderOptions(options, "official-api")
1788
+ });
1789
+ }
1790
+ }
1791
+
1792
+ class FitbitHealthProvider extends BaseHealthProvider {
1793
+ constructor(options) {
1794
+ super({
1795
+ providerKey: "health.fitbit",
1796
+ ...createProviderOptions(options, "official-api")
1797
+ });
1798
+ }
1799
+ }
1800
+
1801
+ class MyFitnessPalHealthProvider extends BaseHealthProvider {
1802
+ constructor(options) {
1803
+ super({
1804
+ providerKey: "health.myfitnesspal",
1805
+ ...createProviderOptions(options, "official-api")
1806
+ });
1807
+ }
1808
+ }
1809
+
1810
+ class EightSleepHealthProvider extends BaseHealthProvider {
1811
+ constructor(options) {
1812
+ super({
1813
+ providerKey: "health.eightsleep",
1814
+ ...createProviderOptions(options, "official-api")
1815
+ });
1816
+ }
1817
+ }
1818
+
1819
+ class PelotonHealthProvider extends BaseHealthProvider {
1820
+ constructor(options) {
1821
+ super({
1822
+ providerKey: "health.peloton",
1823
+ ...createProviderOptions(options, "official-api")
1824
+ });
1825
+ }
1826
+ }
1827
+
1828
+ class UnofficialHealthAutomationProvider extends BaseHealthProvider {
1829
+ constructor(options) {
1830
+ super({
1831
+ ...createProviderOptions(options, "unofficial"),
1832
+ providerKey: options.providerKey
1833
+ });
1834
+ }
1835
+ }
1836
+
1837
+ // src/impls/health-provider-factory.ts
1838
+ import {
1839
+ isUnofficialHealthProviderAllowed,
1840
+ resolveHealthStrategyOrder
1841
+ } from "@contractspec/integration.runtime/runtime";
1842
+ function createHealthProviderFromContext(context, secrets) {
1843
+ const providerKey = context.spec.meta.key;
1844
+ const config = toFactoryConfig(context.config);
1845
+ const strategyOrder = buildStrategyOrder(config);
1846
+ const errors = [];
1847
+ for (const strategy of strategyOrder) {
1848
+ const provider = createHealthProviderForStrategy(providerKey, strategy, config, secrets);
1849
+ if (provider) {
1850
+ return provider;
1851
+ }
1852
+ errors.push(`${strategy}: not available`);
1853
+ }
1854
+ throw new Error(`Unable to resolve health provider for ${providerKey}. Strategies attempted: ${errors.join(", ")}.`);
1855
+ }
1856
+ function createHealthProviderForStrategy(providerKey, strategy, config, secrets) {
1857
+ const options = {
1858
+ transport: strategy,
1859
+ apiBaseUrl: config.apiBaseUrl,
1860
+ mcpUrl: config.mcpUrl,
1861
+ apiKey: getSecretString(secrets, "apiKey"),
1862
+ accessToken: getSecretString(secrets, "accessToken"),
1863
+ mcpAccessToken: getSecretString(secrets, "mcpAccessToken"),
1864
+ webhookSecret: getSecretString(secrets, "webhookSecret")
1865
+ };
1866
+ if (strategy === "aggregator-api" || strategy === "aggregator-mcp") {
1867
+ return new OpenWearablesHealthProvider(options);
1868
+ }
1869
+ if (strategy === "unofficial") {
1870
+ if (!isUnofficialHealthProviderAllowed(providerKey, config)) {
1871
+ return;
1872
+ }
1873
+ if (providerKey !== "health.myfitnesspal" && providerKey !== "health.eightsleep" && providerKey !== "health.peloton" && providerKey !== "health.garmin") {
1874
+ return;
1875
+ }
1876
+ return new UnofficialHealthAutomationProvider({
1877
+ ...options,
1878
+ providerKey
1879
+ });
1880
+ }
1881
+ if (strategy === "official-mcp") {
1882
+ return createOfficialProvider(providerKey, {
1883
+ ...options,
1884
+ transport: "official-mcp"
1885
+ });
1886
+ }
1887
+ return createOfficialProvider(providerKey, options);
1888
+ }
1889
+ function createOfficialProvider(providerKey, options) {
1890
+ switch (providerKey) {
1891
+ case "health.openwearables":
1892
+ return new OpenWearablesHealthProvider(options);
1893
+ case "health.whoop":
1894
+ return new WhoopHealthProvider(options);
1895
+ case "health.apple-health":
1896
+ return new AppleHealthBridgeProvider(options);
1897
+ case "health.oura":
1898
+ return new OuraHealthProvider(options);
1899
+ case "health.strava":
1900
+ return new StravaHealthProvider(options);
1901
+ case "health.garmin":
1902
+ return new GarminHealthProvider(options);
1903
+ case "health.fitbit":
1904
+ return new FitbitHealthProvider(options);
1905
+ case "health.myfitnesspal":
1906
+ return new MyFitnessPalHealthProvider(options);
1907
+ case "health.eightsleep":
1908
+ return new EightSleepHealthProvider(options);
1909
+ case "health.peloton":
1910
+ return new PelotonHealthProvider(options);
1911
+ default:
1912
+ throw new Error(`Unsupported health provider key: ${providerKey}`);
1913
+ }
1914
+ }
1915
+ function toFactoryConfig(config) {
1916
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
1917
+ return {};
1918
+ }
1919
+ const record = config;
1920
+ return {
1921
+ apiBaseUrl: asString(record.apiBaseUrl),
1922
+ mcpUrl: asString(record.mcpUrl),
1923
+ defaultTransport: normalizeTransport(record.defaultTransport),
1924
+ strategyOrder: normalizeTransportArray(record.strategyOrder),
1925
+ allowUnofficial: typeof record.allowUnofficial === "boolean" ? record.allowUnofficial : false,
1926
+ unofficialAllowList: Array.isArray(record.unofficialAllowList) ? record.unofficialAllowList.map((item) => typeof item === "string" ? item : undefined).filter((item) => Boolean(item)) : undefined
1927
+ };
1928
+ }
1929
+ function buildStrategyOrder(config) {
1930
+ const order = resolveHealthStrategyOrder(config);
1931
+ if (!config.defaultTransport) {
1932
+ return order;
1933
+ }
1934
+ const withoutDefault = order.filter((item) => item !== config.defaultTransport);
1935
+ return [config.defaultTransport, ...withoutDefault];
1936
+ }
1937
+ function normalizeTransport(value) {
1938
+ if (typeof value !== "string")
1939
+ return;
1940
+ if (value === "official-api" || value === "official-mcp" || value === "aggregator-api" || value === "aggregator-mcp" || value === "unofficial") {
1941
+ return value;
1942
+ }
1943
+ return;
1944
+ }
1945
+ function normalizeTransportArray(value) {
1946
+ if (!Array.isArray(value))
1947
+ return;
1948
+ const transports = value.map((item) => normalizeTransport(item)).filter((item) => Boolean(item));
1949
+ return transports.length > 0 ? transports : undefined;
1950
+ }
1951
+ function getSecretString(secrets, key) {
1952
+ const value = secrets[key];
1953
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
1954
+ }
1955
+ function asString(value) {
1956
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
1957
+ }
1958
+
1467
1959
  // src/impls/mistral-llm.ts
1468
1960
  import { Mistral } from "@mistralai/mistralai";
1469
1961
 
@@ -2837,7 +3329,7 @@ function mapStatus(status) {
2837
3329
  }
2838
3330
 
2839
3331
  // src/impls/powens-client.ts
2840
- import { URL } from "node:url";
3332
+ import { URL as URL2 } from "node:url";
2841
3333
  var POWENS_BASE_URL = {
2842
3334
  sandbox: "https://api-sandbox.powens.com/v2",
2843
3335
  production: "https://api.powens.com/v2"
@@ -2923,7 +3415,7 @@ class PowensClient {
2923
3415
  });
2924
3416
  }
2925
3417
  async request(options) {
2926
- const url = new URL(options.path, this.baseUrl);
3418
+ const url = new URL2(options.path, this.baseUrl);
2927
3419
  if (options.searchParams) {
2928
3420
  for (const [key, value] of Object.entries(options.searchParams)) {
2929
3421
  if (value === undefined || value === null)
@@ -2993,7 +3485,7 @@ class PowensClient {
2993
3485
  return this.token.accessToken;
2994
3486
  }
2995
3487
  async fetchAccessToken() {
2996
- const url = new URL("/oauth/token", this.baseUrl);
3488
+ const url = new URL2("/oauth/token", this.baseUrl);
2997
3489
  const basicAuth = Buffer.from(`${this.clientId}:${this.clientSecret}`, "utf-8").toString("base64");
2998
3490
  const response = await this.fetchImpl(url, {
2999
3491
  method: "POST",
@@ -4037,6 +4529,10 @@ class IntegrationProviderFactory {
4037
4529
  throw new Error(`Unsupported open banking integration: ${context.spec.meta.key}`);
4038
4530
  }
4039
4531
  }
4532
+ async createHealthProvider(context) {
4533
+ const secrets = await this.loadSecrets(context);
4534
+ return createHealthProviderFromContext(context, secrets);
4535
+ }
4040
4536
  async loadSecrets(context) {
4041
4537
  const cacheKey = context.connection.meta.id;
4042
4538
  if (SECRET_CACHE.has(cacheKey)) {