All files / sdk index.ts

52.32% Statements 45/86
1.13% Branches 1/88
33.33% Functions 3/9
52.32% Lines 45/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 3008x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x   8x                                             15x       15x   15x 15x 15x 15x       15x 15x 2x                 13x         13x             13x 13x 13x 13x 13x 13x   13x               13x 13x 13x 13x       13x     12x   12x                                 6x                                                                                                                                                                                                                                                                                                                                                                
import { ConnectedAccounts } from "./models/connectedAccounts";
import { Apps } from "./models/apps";
import { Actions } from "./models/actions";
import { Triggers } from "./models/triggers";
import { Integrations } from "./models/integrations";
import { ActiveTriggers } from "./models/activeTriggers";
import { BackendClient } from "./models/backendClient";
import { Entity } from "./models/Entity";
import axios from "axios";
import { getPackageJsonDir } from "./utils/projectUtils";
import { isNewerVersion } from "./utils/other";
import { CEG } from "./utils/error";
import { GetConnectorInfoResDTO } from "./client";
import logger, { getLogLevel } from "../utils/logger";
import { SDK_ERROR_CODES } from "./utils/errors/src/constants";
import { getSDKConfig } from "./utils/config";
import ComposioSDKContext from "./utils/composioContext";
import { TELEMETRY_LOGGER } from "./utils/telemetry";
import { TELEMETRY_EVENTS } from "./utils/telemetry/events";
 
export class Composio {
  /**
   * The Composio class serves as the main entry point for interacting with the Composio SDK.
   * It provides access to various models that allow for operations on connected accounts, apps,
   * actions, triggers, integrations, and active triggers.
   */
  backendClient: BackendClient;
  connectedAccounts: ConnectedAccounts;
  apps: Apps;
  actions: Actions;
  triggers: Triggers;
  integrations: Integrations;
  activeTriggers: ActiveTriggers;
 
  /**
   * Initializes a new instance of the Composio class.
   *
   * @param {string} [apiKey] - The API key for authenticating with the Composio backend. Can also be set locally in an environment variable.
   * @param {string} [baseUrl] - The base URL for the Composio backend. By default, it is set to the production URL.
   * @param {string} [runtime] - The runtime environment for the SDK.
   */
  constructor(apiKey?: string, baseUrl?: string, runtime?: string) {
    // // Parse the base URL and API key, falling back to environment variables or defaults if not provided.
    const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
      baseUrl,
      apiKey
    );
    const loggingLevel = getLogLevel();
 
    ComposioSDKContext.apiKey = apiKeyParsed;
    ComposioSDKContext.baseURL = baseURLParsed;
    ComposioSDKContext.frameworkRuntime = runtime;
    ComposioSDKContext.composioVersion = require(
      getPackageJsonDir() + "/package.json"
    ).version;
 
    TELEMETRY_LOGGER.manualTelemetry(TELEMETRY_EVENTS.SDK_INITIALIZED, {});
    if (!apiKeyParsed) {
      throw CEG.getCustomError(SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE, {
        message: "🔑 API Key is not provided",
        description:
          "You need to provide it in the constructor or as an environment variable COMPOSIO_API_KEY",
        possibleFix:
          "Please provide a valid API Key. You can get it from https://app.composio.dev/settings",
      });
    }
 
    logger.info(
      `Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`
    );
 
    // Initialize the BackendClient with the parsed API key and base URL.
    this.backendClient = new BackendClient(
      apiKeyParsed,
      baseURLParsed,
      runtime
    );
 
    // Instantiate models with dependencies as needed.
    this.connectedAccounts = new ConnectedAccounts(this.backendClient);
    this.triggers = new Triggers(this.backendClient);
    this.apps = new Apps(this.backendClient);
    this.actions = new Actions(this.backendClient);
    this.integrations = new Integrations(this.backendClient);
    this.activeTriggers = new ActiveTriggers(this.backendClient);
 
    this.checkForLatestVersionFromNPM();
  }
 
  /**
   * Checks for the latest version of the Composio SDK from NPM.
   * If a newer version is available, it logs a warning to the console.
   */
  async checkForLatestVersionFromNPM() {
    try {
      const packageName = "composio-core";
      const packageJsonDir = getPackageJsonDir();
      const currentVersionFromPackageJson = require(
        packageJsonDir + "/package.json"
      ).version;
 
      const response = await axios.get(
        `https://registry.npmjs.org/${packageName}/latest`
      );
      const latestVersion = response.data.version;
 
      Iif (isNewerVersion(latestVersion, currentVersionFromPackageJson)) {
        console.warn(
          `🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
        );
      }
    } catch (error) {
      // Ignore and do nothing
    }
  }
 
  /**
   * Retrieves an Entity instance associated with a given ID.
   *
   * @param {string} [id='default'] - The ID of the entity to retrieve.
   * @returns {Entity} An instance of the Entity class.
   */
  getEntity(id: string = "default"): Entity {
    return new Entity(this.backendClient, id);
  }
 
  async getExpectedParamsForUser(
    params: {
      app?: string;
      integrationId?: string;
      entityId?: string;
      authScheme?:
        | "OAUTH2"
        | "OAUTH1"
        | "API_KEY"
        | "BASIC"
        | "BEARER_TOKEN"
        | "BASIC_WITH_JWT";
    } = {}
  ): Promise<{
    expectedInputFields: GetConnectorInfoResDTO["expectedInputFields"];
    integrationId: string;
    authScheme:
      | "OAUTH2"
      | "OAUTH1"
      | "API_KEY"
      | "BASIC"
      | "BEARER_TOKEN"
      | "BASIC_WITH_JWT";
  }> {
    const { app } = params;
    let { integrationId } = params;
    Iif (integrationId === null && app === null) {
      throw new Error("Both `integration_id` and `app` cannot be None");
    }
 
    Iif (!integrationId) {
      try {
        const integrations = await this.integrations.list({
          appName: app!,
          showDisabled: false,
        });
        Iif (params.authScheme && integrations) {
          integrations.items = integrations.items.filter(
            (integration: any) => integration.authScheme === params.authScheme
          );
        }
        integrationId = (integrations?.items[0] as any)?.id;
      } catch (_) {
        // do nothing
      }
    }
 
    let integration = integrationId
      ? await this.integrations.get({
          integrationId: integrationId!,
        })
      : undefined;
 
    Iif (integration) {
      return {
        expectedInputFields: integration.expectedInputFields,
        integrationId: integration.id!,
        authScheme: integration.authScheme as
          | "OAUTH2"
          | "OAUTH1"
          | "API_KEY"
          | "BASIC"
          | "BEARER_TOKEN"
          | "BASIC_WITH_JWT",
      };
    }
 
    const appInfo = await this.apps.get({
      appKey: app!.toLocaleLowerCase(),
    });
 
    const preferredAuthScheme = [
      "OAUTH2",
      "OAUTH1",
      "API_KEY",
      "BASIC",
      "BEARER_TOKEN",
      "BASIC_WITH_JWT",
    ];
 
    let schema: (typeof preferredAuthScheme)[number] | undefined =
      params.authScheme;
 
    Iif (!schema) {
      for (const scheme of preferredAuthScheme) {
        Iif (
          appInfo.auth_schemes
            ?.map((_authScheme: any) => _authScheme.mode)
            .includes(scheme)
        ) {
          schema = scheme;
          break;
        }
      }
    }
 
    const areNoFieldsRequiredForIntegration =
      (appInfo.testConnectors?.length ?? 0) > 0 ||
      ((
        appInfo.auth_schemes?.find(
          (_authScheme: any) => _authScheme.mode === schema
        ) as any
      )?.fields?.filter((field: any) => !field.expected_from_customer)
        ?.length ?? 0) == 0;
 
    Iif (!areNoFieldsRequiredForIntegration) {
      throw new Error(
        `No default credentials available for this app, please create new integration by going to app.composio.dev or through CLI - composio add ${appInfo.key}`
      );
    }
 
    const timestamp = new Date().toISOString().replace(/[-:.]/g, "");
    const hasRelevantTestConnectors = params.authScheme
      ? appInfo.testConnectors?.filter(
          (connector: any) => connector.authScheme === params.authScheme
        )?.length! > 0
      : appInfo.testConnectors?.length! > 0;
    Iif (hasRelevantTestConnectors) {
      integration = await this.integrations.create({
        appId: appInfo.appId,
        name: `integration_${timestamp}`,
        authScheme: schema,
        authConfig: {},
        useComposioAuth: true,
      });
 
      return {
        expectedInputFields: integration?.expectedInputFields!,
        integrationId: integration?.id!,
        authScheme: integration?.authScheme as
          | "OAUTH2"
          | "OAUTH1"
          | "API_KEY"
          | "BASIC"
          | "BEARER_TOKEN"
          | "BASIC_WITH_JWT",
      };
    }
 
    Iif (!schema) {
      throw new Error(
        `No supported auth scheme found for \`${String(app)}\`, ` +
          "Please create an integration and use the ID to " +
          "get the expected parameters."
      );
    }
 
    integration = await this.integrations.create({
      appId: appInfo.appId,
      name: `integration_${timestamp}`,
      authScheme: schema,
      authConfig: {},
      useComposioAuth: false,
    });
 
    Iif (!integration) {
      throw new Error(
        "An unexpected error occurred while creating the integration, please create an integration manually and use its ID to get the expected parameters"
      );
    }
    return {
      expectedInputFields: integration.expectedInputFields,
      integrationId: integration.id!,
      authScheme: integration.authScheme as
        | "OAUTH2"
        | "OAUTH1"
        | "API_KEY"
        | "BASIC"
        | "BEARER_TOKEN"
        | "BASIC_WITH_JWT",
    };
  }
}