@composio/core 0.4.0 → 0.5.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/dist/{chunk-SfbczIpV.mjs → chunk-0j-ceAHr.mjs} +3 -4
- package/dist/chunk-CQwRTUmo.cjs +53 -0
- package/dist/fileUtils-CJjp8sBn.cjs +931 -0
- package/dist/fileUtils-XEoNI39Q.mjs +852 -0
- package/dist/files.types-B7P5A1Z5.d.mts +17 -0
- package/dist/files.types-D-RzIOHq.d.cts +17 -0
- package/dist/index.cjs +363 -1069
- package/dist/index.d.cts +656 -384
- package/dist/index.d.mts +655 -384
- package/dist/index.mjs +251 -920
- package/dist/models/Files.node.cjs +38 -0
- package/dist/models/Files.node.d.cts +41 -0
- package/dist/models/Files.node.d.mts +41 -0
- package/dist/models/Files.node.mjs +39 -0
- package/dist/models/Files.workerd.cjs +29 -0
- package/dist/models/Files.workerd.d.cts +13 -0
- package/dist/models/Files.workerd.d.mts +13 -0
- package/dist/models/Files.workerd.mjs +28 -0
- package/dist/platform/node.cjs +46 -0
- package/dist/platform/node.d.cts +11 -0
- package/dist/platform/node.d.mts +11 -0
- package/dist/platform/node.mjs +42 -0
- package/dist/platform/workerd.cjs +36 -0
- package/dist/platform/workerd.d.cts +12 -0
- package/dist/platform/workerd.d.mts +12 -0
- package/dist/platform/workerd.mjs +35 -0
- package/dist/types-BaUqjuX3.d.mts +56 -0
- package/dist/types-BrsW5suw.d.cts +56 -0
- package/generated/index.d.ts +6 -0
- package/generated/index.js +18 -0
- package/package.json +74 -14
- package/src/platform/index.ts +2 -0
- package/src/platform/node.ts +51 -0
- package/src/platform/types.ts +60 -0
- package/src/platform/workerd.ts +57 -0
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import "./chunk-0j-ceAHr.mjs";
|
|
2
|
+
import { a as logger_default, c as DEFAULT_BASE_URL, d as constants_exports, f as getEnvVariable, i as ComposioError, l as IS_DEVELOPMENT_OR_CI, n as getFileDataAfterUploadingToS3, o as COMPOSIO_DIR, p as getEnvsWithPrefix, r as telemetry, s as COMPOSIO_LOG_LEVEL, t as downloadFileFromS3, u as USER_DATA_FILE_NAME } from "./fileUtils-XEoNI39Q.mjs";
|
|
3
|
+
import ComposioClient, { APIError } from "@composio/client";
|
|
3
4
|
import z, { ZodError, z as z$1 } from "zod/v3";
|
|
4
5
|
import * as zodToJsonSchema from "zod-to-json-schema";
|
|
5
|
-
import chalk from "chalk";
|
|
6
|
-
import { v4 } from "uuid";
|
|
7
|
-
import crypto from "crypto";
|
|
8
|
-
import pathModule from "path";
|
|
9
|
-
import { APIError as APIError$1 } from "openai";
|
|
10
6
|
import * as crypto$1 from "node:crypto";
|
|
7
|
+
import { platform } from "#platform";
|
|
8
|
+
import { APIError as APIError$1 } from "openai";
|
|
11
9
|
import semver from "semver";
|
|
10
|
+
import { Files } from "#files";
|
|
12
11
|
import { jsonSchemaToZod } from "@composio/json-schema-to-zod";
|
|
13
12
|
|
|
14
13
|
//#region src/types/authConfigs.types.ts
|
|
@@ -915,350 +914,6 @@ const ToolProxyParamsSchema = z$1.object({
|
|
|
915
914
|
customConnectionData: CustomConnectionDataSchema.describe("DEPRECATED: This field is deprecated and will be removed in the future.").optional()
|
|
916
915
|
});
|
|
917
916
|
|
|
918
|
-
//#endregion
|
|
919
|
-
//#region src/utils/env.ts
|
|
920
|
-
const getEnvVariable = (name, defaultValue = void 0) => {
|
|
921
|
-
try {
|
|
922
|
-
return process.env[name] || defaultValue;
|
|
923
|
-
} catch (_e) {
|
|
924
|
-
return defaultValue;
|
|
925
|
-
}
|
|
926
|
-
};
|
|
927
|
-
/**
|
|
928
|
-
* Method to return all the envs based on a specific prefix
|
|
929
|
-
* @param prefix
|
|
930
|
-
* @example
|
|
931
|
-
* COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00
|
|
932
|
-
* COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00
|
|
933
|
-
* COMPOSIO_TOOLKIT_VERSION_GMAIL=latest
|
|
934
|
-
* @returns {Record<string, unknown>}
|
|
935
|
-
* @returns
|
|
936
|
-
*/
|
|
937
|
-
const getEnvsWithPrefix = (prefix) => {
|
|
938
|
-
try {
|
|
939
|
-
if (process && process.env) return Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith(prefix)));
|
|
940
|
-
else return {};
|
|
941
|
-
} catch (error) {
|
|
942
|
-
return {};
|
|
943
|
-
}
|
|
944
|
-
};
|
|
945
|
-
|
|
946
|
-
//#endregion
|
|
947
|
-
//#region src/utils/constants.ts
|
|
948
|
-
var constants_exports = /* @__PURE__ */ __export({
|
|
949
|
-
CLIENT_PUSHER_KEY: () => CLIENT_PUSHER_KEY,
|
|
950
|
-
COMPOSIO_DIR: () => COMPOSIO_DIR,
|
|
951
|
-
COMPOSIO_LOG_LEVEL: () => COMPOSIO_LOG_LEVEL,
|
|
952
|
-
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
953
|
-
DEFAULT_WEB_URL: () => DEFAULT_WEB_URL,
|
|
954
|
-
IS_DEVELOPMENT_OR_CI: () => IS_DEVELOPMENT_OR_CI,
|
|
955
|
-
TELEMETRY_URL: () => TELEMETRY_URL$1,
|
|
956
|
-
TEMP_FILES_DIRECTORY_NAME: () => TEMP_FILES_DIRECTORY_NAME,
|
|
957
|
-
USER_DATA_FILE_NAME: () => USER_DATA_FILE_NAME
|
|
958
|
-
});
|
|
959
|
-
const COMPOSIO_DIR = ".composio";
|
|
960
|
-
const USER_DATA_FILE_NAME = "user_data.json";
|
|
961
|
-
const TEMP_FILES_DIRECTORY_NAME = "files";
|
|
962
|
-
const DEFAULT_BASE_URL = "https://backend.composio.dev";
|
|
963
|
-
const DEFAULT_WEB_URL = "https://platform.composio.dev";
|
|
964
|
-
const TELEMETRY_URL$1 = "https://app.composio.dev";
|
|
965
|
-
const CLIENT_PUSHER_KEY = getEnvVariable("CLIENT_PUSHER_KEY") || "ff9f18c208855d77a152";
|
|
966
|
-
const COMPOSIO_LOG_LEVEL = getEnvVariable("COMPOSIO_LOG_LEVEL");
|
|
967
|
-
const IS_DEVELOPMENT_OR_CI = getEnvVariable("DEVELOPMENT") || getEnvVariable("CI") || false;
|
|
968
|
-
|
|
969
|
-
//#endregion
|
|
970
|
-
//#region src/utils/logger.ts
|
|
971
|
-
const LOG_LEVELS = {
|
|
972
|
-
silent: -1,
|
|
973
|
-
error: 0,
|
|
974
|
-
warn: 1,
|
|
975
|
-
info: 2,
|
|
976
|
-
debug: 3
|
|
977
|
-
};
|
|
978
|
-
/**
|
|
979
|
-
* Get the current log level from environment variables.
|
|
980
|
-
* Defaults to 'info' if not set or invalid.
|
|
981
|
-
* @returns {LogLevel} The current log level
|
|
982
|
-
*/
|
|
983
|
-
const getLogLevel = () => {
|
|
984
|
-
const envLevel = (COMPOSIO_LOG_LEVEL ?? "info")?.toLowerCase();
|
|
985
|
-
return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
|
|
986
|
-
};
|
|
987
|
-
var Logger = class {
|
|
988
|
-
level;
|
|
989
|
-
includeTimestamp;
|
|
990
|
-
console;
|
|
991
|
-
constructor(options = {}) {
|
|
992
|
-
this.level = options.level ?? getLogLevel();
|
|
993
|
-
this.includeTimestamp = options.includeTimestamp ?? true;
|
|
994
|
-
this.console = console;
|
|
995
|
-
}
|
|
996
|
-
formatMessage(args) {
|
|
997
|
-
const formattedArgs = args.map((arg, index) => {
|
|
998
|
-
if (typeof arg === "object") return JSON.stringify(arg);
|
|
999
|
-
else {
|
|
1000
|
-
if (index === 0) if (args.length > 1) return chalk.yellow(`${arg}`);
|
|
1001
|
-
else return String(arg);
|
|
1002
|
-
return String(arg);
|
|
1003
|
-
}
|
|
1004
|
-
}).join("\n");
|
|
1005
|
-
if (!this.includeTimestamp) return formattedArgs;
|
|
1006
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
1007
|
-
return `${chalk.gray(timestamp)} - ${formattedArgs}`;
|
|
1008
|
-
}
|
|
1009
|
-
shouldLog(level) {
|
|
1010
|
-
return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
|
|
1011
|
-
}
|
|
1012
|
-
error(...args) {
|
|
1013
|
-
if (this.shouldLog("error")) this.console.error(this.formatMessage(args));
|
|
1014
|
-
}
|
|
1015
|
-
warn(...args) {
|
|
1016
|
-
if (this.shouldLog("warn")) this.console.warn(this.formatMessage(args));
|
|
1017
|
-
}
|
|
1018
|
-
info(...args) {
|
|
1019
|
-
if (this.shouldLog("info")) this.console.info(this.formatMessage(args));
|
|
1020
|
-
}
|
|
1021
|
-
debug(...args) {
|
|
1022
|
-
if (this.shouldLog("debug")) this.console.debug(this.formatMessage(args));
|
|
1023
|
-
}
|
|
1024
|
-
};
|
|
1025
|
-
const logger = new Logger();
|
|
1026
|
-
var logger_default = logger;
|
|
1027
|
-
|
|
1028
|
-
//#endregion
|
|
1029
|
-
//#region src/errors/ComposioError.ts
|
|
1030
|
-
/**
|
|
1031
|
-
* @fileoverview Error class for Composio.
|
|
1032
|
-
*
|
|
1033
|
-
* This error class is used to create custom errors for Composio.
|
|
1034
|
-
* It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
|
|
1035
|
-
*
|
|
1036
|
-
* @author Musthaq Ahamad <musthaq@composio.dev>
|
|
1037
|
-
* @module errors/ComposioError
|
|
1038
|
-
* @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
|
|
1039
|
-
*/
|
|
1040
|
-
/**
|
|
1041
|
-
* Base error class for all Composio errors
|
|
1042
|
-
*/
|
|
1043
|
-
var ComposioError = class ComposioError extends Error {
|
|
1044
|
-
/** @readonly Error name */
|
|
1045
|
-
name = "ComposioError";
|
|
1046
|
-
code;
|
|
1047
|
-
possibleFixes;
|
|
1048
|
-
errorId;
|
|
1049
|
-
/**
|
|
1050
|
-
* Creates a new ComposioError
|
|
1051
|
-
* @param message Error message
|
|
1052
|
-
* @param options Additional error options
|
|
1053
|
-
*/
|
|
1054
|
-
constructor(message, options = {}) {
|
|
1055
|
-
super(message);
|
|
1056
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
1057
|
-
const statusCode = options.statusCode || (options.cause instanceof BadRequestError ? options.cause.status : void 0);
|
|
1058
|
-
this.code = `TS-SDK::${options.code}`;
|
|
1059
|
-
this.possibleFixes = options.possibleFixes;
|
|
1060
|
-
this.definePropertyIfExists("statusCode", statusCode);
|
|
1061
|
-
this.definePropertyIfExists("cause", options.cause);
|
|
1062
|
-
const combinedStack = options.cause instanceof Error ? ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
|
|
1063
|
-
this.definePropertyIfExists("stack", combinedStack);
|
|
1064
|
-
if (options.meta && Object.keys(options.meta).length > 0) this.definePropertyIfExists("meta", options.meta);
|
|
1065
|
-
}
|
|
1066
|
-
/**
|
|
1067
|
-
* Helper method to define a property only if it has a value
|
|
1068
|
-
* @param propertyName Name of the property to define
|
|
1069
|
-
* @param value Value to assign to the property
|
|
1070
|
-
* @private
|
|
1071
|
-
*/
|
|
1072
|
-
definePropertyIfExists(propertyName, value) {
|
|
1073
|
-
if (value !== void 0) Object.defineProperty(this, propertyName, {
|
|
1074
|
-
value,
|
|
1075
|
-
enumerable: true,
|
|
1076
|
-
writable: false,
|
|
1077
|
-
configurable: true
|
|
1078
|
-
});
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Helper method to combine stack traces when wrapping errors
|
|
1082
|
-
* This ensures the full call chain is preserved
|
|
1083
|
-
* @param originalStack The stack of the error being wrapped
|
|
1084
|
-
* @param currentStack The stack of the wrapper error
|
|
1085
|
-
* @returns Combined stack trace
|
|
1086
|
-
* @private
|
|
1087
|
-
*/
|
|
1088
|
-
static combineStackTraces(originalStack, currentStack) {
|
|
1089
|
-
if (!originalStack) return currentStack;
|
|
1090
|
-
if (!currentStack) return originalStack;
|
|
1091
|
-
const currentHeader = currentStack.split("\n")[0];
|
|
1092
|
-
const originalStackBody = originalStack.split("\n").slice(1).join("\n");
|
|
1093
|
-
return `${currentHeader}\n${currentStack.split("\n").slice(1).join("\n")}\n\nCaused by:\n${originalStackBody}`;
|
|
1094
|
-
}
|
|
1095
|
-
/**
|
|
1096
|
-
* Extract and normalize error data for formatting
|
|
1097
|
-
* @param includeStack Whether to include stack trace information
|
|
1098
|
-
* @returns Structured error data for formatting
|
|
1099
|
-
* @private
|
|
1100
|
-
*/
|
|
1101
|
-
getErrorData(includeStack = false) {
|
|
1102
|
-
const data = {
|
|
1103
|
-
name: this.name,
|
|
1104
|
-
message: this.message
|
|
1105
|
-
};
|
|
1106
|
-
const { cause, code, stack, statusCode, meta, possibleFixes } = this;
|
|
1107
|
-
if (cause !== void 0) {
|
|
1108
|
-
const rawCause = cause;
|
|
1109
|
-
data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
|
|
1110
|
-
}
|
|
1111
|
-
if (code) data.code = code;
|
|
1112
|
-
if (statusCode !== void 0) data.statusCode = statusCode;
|
|
1113
|
-
if (meta) data.meta = meta;
|
|
1114
|
-
if (possibleFixes) data.possibleFixes = possibleFixes;
|
|
1115
|
-
if (includeStack && stack) if (stack.includes("Caused by:")) {
|
|
1116
|
-
const [currentStack, causeStack] = stack.split("Caused by:");
|
|
1117
|
-
data.stack = [
|
|
1118
|
-
...currentStack.split("\n").slice(1),
|
|
1119
|
-
"Caused by:",
|
|
1120
|
-
...causeStack.split("\n")
|
|
1121
|
-
];
|
|
1122
|
-
} else data.stack = stack.split("\n").slice(1);
|
|
1123
|
-
return data;
|
|
1124
|
-
}
|
|
1125
|
-
/**
|
|
1126
|
-
* Prints a user-friendly, colorful representation of the error to the logger
|
|
1127
|
-
* @param includeStack Whether to include the stack trace in the output (default: false)
|
|
1128
|
-
*/
|
|
1129
|
-
prettyPrint(includeStack = false) {
|
|
1130
|
-
const data = this.getErrorData(includeStack);
|
|
1131
|
-
let output = "\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(data.message) + "\n";
|
|
1132
|
-
if (data.code) output += chalk.yellow(`Error Code: ${data.code}`) + "\n";
|
|
1133
|
-
if (data.statusCode !== void 0) output += chalk.yellow(`Status: ${data.statusCode}`) + "\n";
|
|
1134
|
-
if (data.cause) {
|
|
1135
|
-
output += chalk.gray("Reason:") + "\n";
|
|
1136
|
-
output += " " + chalk.white(data.cause) + "\n";
|
|
1137
|
-
}
|
|
1138
|
-
if (data.meta) {
|
|
1139
|
-
output += chalk.gray("Additional Information:") + "\n";
|
|
1140
|
-
output += " " + chalk.white(JSON.stringify(data.meta, null, 2).replace(/\n/g, "\n ")) + "\n";
|
|
1141
|
-
}
|
|
1142
|
-
if (data.possibleFixes?.length) {
|
|
1143
|
-
output += "\n" + chalk.cyan.bold("Try the following:") + "\n";
|
|
1144
|
-
const fixes = data.possibleFixes?.map((fix, index) => ` ${index + 1}. ` + chalk.white(fix));
|
|
1145
|
-
output += fixes?.join("\n") + "\n";
|
|
1146
|
-
}
|
|
1147
|
-
if (data.stack?.length) {
|
|
1148
|
-
output += "\n" + chalk.gray("Stack Trace:") + "\n";
|
|
1149
|
-
output += chalk.gray(data.stack.join("\n")) + "\n";
|
|
1150
|
-
}
|
|
1151
|
-
output += "\n";
|
|
1152
|
-
logger_default.error(output);
|
|
1153
|
-
}
|
|
1154
|
-
/**
|
|
1155
|
-
* Static factory method to create and pretty print an error in one step
|
|
1156
|
-
* @param message Error message
|
|
1157
|
-
* @param options Error options
|
|
1158
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1159
|
-
* @returns The created error instance
|
|
1160
|
-
*/
|
|
1161
|
-
static createAndPrint(message, options = {}, includeStack = false) {
|
|
1162
|
-
const error = new ComposioError(message, options);
|
|
1163
|
-
error.prettyPrint(includeStack);
|
|
1164
|
-
return error;
|
|
1165
|
-
}
|
|
1166
|
-
/**
|
|
1167
|
-
* Utility function to handle errors in a consistent way
|
|
1168
|
-
* This properly displays the error without throwing
|
|
1169
|
-
* @param error The error to handle
|
|
1170
|
-
* @param options Options for error handling
|
|
1171
|
-
*/
|
|
1172
|
-
static handle(error, options = {}) {
|
|
1173
|
-
const { includeStack = false, exitProcess = false } = options;
|
|
1174
|
-
if (error instanceof ComposioError) error.prettyPrint(includeStack);
|
|
1175
|
-
else if (error instanceof ZodError) this.handleZodError(error, includeStack);
|
|
1176
|
-
else if (error instanceof Error) this.handleStandardError(error, includeStack);
|
|
1177
|
-
else this.handleUnknownError(error);
|
|
1178
|
-
if (exitProcess) this.throwError(error);
|
|
1179
|
-
}
|
|
1180
|
-
/**
|
|
1181
|
-
* Utility function to handle errors and then throw them
|
|
1182
|
-
* This properly displays the error and then throws it, allowing callers to catch it.
|
|
1183
|
-
* Use this for fatal errors that should stop execution.
|
|
1184
|
-
* @param error The error to handle and throw
|
|
1185
|
-
* @param includeStack Whether to include the stack trace in the output
|
|
1186
|
-
* @throws ComposioError - Always throws after displaying the error
|
|
1187
|
-
*/
|
|
1188
|
-
static handleAndThrow(error, includeStack = false) {
|
|
1189
|
-
this.handle(error, { includeStack });
|
|
1190
|
-
this.throwError(error);
|
|
1191
|
-
}
|
|
1192
|
-
/**
|
|
1193
|
-
* Helper method to throw an error as a ComposioError
|
|
1194
|
-
* @param error The error to throw
|
|
1195
|
-
* @private
|
|
1196
|
-
*/
|
|
1197
|
-
static throwError(error) {
|
|
1198
|
-
if (error instanceof ComposioError) throw error;
|
|
1199
|
-
else if (error instanceof Error) throw new ComposioError(error.message, { cause: error });
|
|
1200
|
-
else throw new ComposioError(String(error));
|
|
1201
|
-
}
|
|
1202
|
-
/**
|
|
1203
|
-
* Helper method to handle Zod validation errors
|
|
1204
|
-
* @param error The Zod error to handle
|
|
1205
|
-
* @param includeStack Whether to include the stack trace
|
|
1206
|
-
* @private
|
|
1207
|
-
*/
|
|
1208
|
-
static handleZodError(error, includeStack) {
|
|
1209
|
-
logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(error.message));
|
|
1210
|
-
logger_default.error(chalk.gray("Invalid parameters:"));
|
|
1211
|
-
error.errors.forEach((err) => {
|
|
1212
|
-
logger_default.error(chalk.yellow(err.path.join(".")) + " " + chalk.white(err.message));
|
|
1213
|
-
});
|
|
1214
|
-
logger_default.error(chalk.gray("Expected parameters:"));
|
|
1215
|
-
error.errors.forEach((err) => {
|
|
1216
|
-
logger_default.error(chalk.yellow(err.path.join(".")) + " " + chalk.white(err.message));
|
|
1217
|
-
});
|
|
1218
|
-
if (includeStack) {
|
|
1219
|
-
logger_default.error("\n" + chalk.gray("Validation Errors:"));
|
|
1220
|
-
error.errors.forEach((err) => {
|
|
1221
|
-
const path = err.path.join(".");
|
|
1222
|
-
logger_default.error(chalk.gray(" • ") + chalk.yellow(path ? `${path}: ` : "") + chalk.white(err.message));
|
|
1223
|
-
});
|
|
1224
|
-
if (error.stack) {
|
|
1225
|
-
logger_default.error("\n" + chalk.gray("Stack Trace:"));
|
|
1226
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1227
|
-
logger_default.error(chalk.gray(stackLines.join("\n")));
|
|
1228
|
-
}
|
|
1229
|
-
}
|
|
1230
|
-
logger_default.error("");
|
|
1231
|
-
}
|
|
1232
|
-
/**
|
|
1233
|
-
* Helper method to handle standard Error objects
|
|
1234
|
-
* @param error The standard error to handle
|
|
1235
|
-
* @param includeStack Whether to include the stack trace
|
|
1236
|
-
* @private
|
|
1237
|
-
*/
|
|
1238
|
-
static handleStandardError(error, includeStack) {
|
|
1239
|
-
logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(error.message));
|
|
1240
|
-
if (includeStack && error.stack) {
|
|
1241
|
-
logger_default.error("\n" + chalk.gray("Stack Trace:"));
|
|
1242
|
-
const stackLines = error.stack.split("\n").slice(1);
|
|
1243
|
-
logger_default.error(chalk.gray(stackLines.join("\n")));
|
|
1244
|
-
}
|
|
1245
|
-
logger_default.error("");
|
|
1246
|
-
}
|
|
1247
|
-
/**
|
|
1248
|
-
* Helper method to handle unknown error types
|
|
1249
|
-
* @param error The unknown error value
|
|
1250
|
-
* @private
|
|
1251
|
-
*/
|
|
1252
|
-
static handleUnknownError(error) {
|
|
1253
|
-
logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold("Unknown error occurred"));
|
|
1254
|
-
if (error !== null && error !== void 0) {
|
|
1255
|
-
logger_default.error(chalk.gray("Error details:"));
|
|
1256
|
-
logger_default.error(" " + chalk.white(String(error)));
|
|
1257
|
-
}
|
|
1258
|
-
logger_default.error("");
|
|
1259
|
-
}
|
|
1260
|
-
};
|
|
1261
|
-
|
|
1262
917
|
//#endregion
|
|
1263
918
|
//#region src/errors/ConnectedAccountsErrors.ts
|
|
1264
919
|
const ConnectedAccountErrorCodes = {
|
|
@@ -1471,290 +1126,6 @@ const handleToolExecutionError = (tool, actualError) => {
|
|
|
1471
1126
|
});
|
|
1472
1127
|
};
|
|
1473
1128
|
|
|
1474
|
-
//#endregion
|
|
1475
|
-
//#region src/types/telemetry.types.ts
|
|
1476
|
-
const TELEMETRY_EVENTS = {
|
|
1477
|
-
SDK_INITIALIZED: "SDK_INITIALIZED",
|
|
1478
|
-
SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
|
|
1479
|
-
SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
|
|
1480
|
-
CLI_INVOKED: "CLI_INVOKED"
|
|
1481
|
-
};
|
|
1482
|
-
|
|
1483
|
-
//#endregion
|
|
1484
|
-
//#region src/telemetry/BatchProcessor.ts
|
|
1485
|
-
var BatchProcessor = class {
|
|
1486
|
-
batch = [];
|
|
1487
|
-
time;
|
|
1488
|
-
batchSize;
|
|
1489
|
-
processBatchCallback;
|
|
1490
|
-
timer = null;
|
|
1491
|
-
constructor(time = 2e3, batchSize = 100, processBatchCallback) {
|
|
1492
|
-
this.batch = [];
|
|
1493
|
-
this.time = time;
|
|
1494
|
-
this.batchSize = batchSize;
|
|
1495
|
-
this.processBatchCallback = processBatchCallback;
|
|
1496
|
-
}
|
|
1497
|
-
pushItem(item) {
|
|
1498
|
-
this.batch.push(item);
|
|
1499
|
-
if (this.batch.length >= this.batchSize) this.processBatch();
|
|
1500
|
-
else if (!this.timer) this.timer = setTimeout(() => this.processBatch(), this.time);
|
|
1501
|
-
}
|
|
1502
|
-
processBatch() {
|
|
1503
|
-
if (this.batch.length > 0) {
|
|
1504
|
-
this.processBatchCallback(this.batch);
|
|
1505
|
-
this.batch = [];
|
|
1506
|
-
}
|
|
1507
|
-
if (this.timer) {
|
|
1508
|
-
clearTimeout(this.timer);
|
|
1509
|
-
this.timer = null;
|
|
1510
|
-
}
|
|
1511
|
-
}
|
|
1512
|
-
};
|
|
1513
|
-
|
|
1514
|
-
//#endregion
|
|
1515
|
-
//#region src/utils/uuid.ts
|
|
1516
|
-
function getRandomUUID() {
|
|
1517
|
-
return v4();
|
|
1518
|
-
}
|
|
1519
|
-
function getRandomShortId() {
|
|
1520
|
-
return getRandomUUID().slice(0, 8).replace(/-/g, "");
|
|
1521
|
-
}
|
|
1522
|
-
|
|
1523
|
-
//#endregion
|
|
1524
|
-
//#region src/services/telemetry/TelemetryService.ts
|
|
1525
|
-
const TELEMETRY_URL = "https://telemetry.composio.dev/v1";
|
|
1526
|
-
var TelemetryService = class {
|
|
1527
|
-
/**
|
|
1528
|
-
* Sends a metric to the Telemetry API.
|
|
1529
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1530
|
-
* @returns The response from the Telemetry API.
|
|
1531
|
-
*/
|
|
1532
|
-
static async sendMetric(payload) {
|
|
1533
|
-
try {
|
|
1534
|
-
return await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
|
|
1535
|
-
method: "POST",
|
|
1536
|
-
headers: { "Content-Type": "application/json" },
|
|
1537
|
-
body: JSON.stringify(payload)
|
|
1538
|
-
});
|
|
1539
|
-
} catch (error) {
|
|
1540
|
-
logger_default.debug("Error sending metric telemetry", error);
|
|
1541
|
-
}
|
|
1542
|
-
}
|
|
1543
|
-
/**
|
|
1544
|
-
* Sends an error log to the Telemetry API.
|
|
1545
|
-
* @param payload - The payload to send to the Telemetry API.
|
|
1546
|
-
* @returns The response from the Telemetry API.
|
|
1547
|
-
*/
|
|
1548
|
-
static async sendErrorLog(payload) {
|
|
1549
|
-
try {
|
|
1550
|
-
return await fetch(`${TELEMETRY_URL}/errors`, {
|
|
1551
|
-
method: "POST",
|
|
1552
|
-
headers: { "Content-Type": "application/json" },
|
|
1553
|
-
body: JSON.stringify(payload)
|
|
1554
|
-
});
|
|
1555
|
-
} catch (error) {
|
|
1556
|
-
logger_default.debug("Error sending error telemetry", error);
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
};
|
|
1560
|
-
|
|
1561
|
-
//#endregion
|
|
1562
|
-
//#region src/telemetry/Telemetry.ts
|
|
1563
|
-
/**
|
|
1564
|
-
* The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
|
|
1565
|
-
*
|
|
1566
|
-
* This class is used to instrument the telemetry for the given instance and send the telemetry to the server.
|
|
1567
|
-
* This class is also used to create a global error handler for the given instance.
|
|
1568
|
-
*
|
|
1569
|
-
* @example
|
|
1570
|
-
*
|
|
1571
|
-
* const telemetry = new Telemetry({...});
|
|
1572
|
-
* const composio = new Composio({...})
|
|
1573
|
-
*
|
|
1574
|
-
* telemetry.instrument(composio);
|
|
1575
|
-
* telemetry.instrument(composio.tools);
|
|
1576
|
-
* telemetry.instrument(composio.toolkits);
|
|
1577
|
-
* telemetry.instrument(composio.triggers);
|
|
1578
|
-
*
|
|
1579
|
-
*/
|
|
1580
|
-
var TelemetryTransport = class {
|
|
1581
|
-
telemetryMetadata;
|
|
1582
|
-
isTelemetryDisabled = true;
|
|
1583
|
-
telemetrySource;
|
|
1584
|
-
telemetrySourceName = "typescript-sdk";
|
|
1585
|
-
telemetryServiceName = "sdk";
|
|
1586
|
-
telemetryLanguage = "typescript";
|
|
1587
|
-
batchProcessor = new BatchProcessor(200, 10, async (data) => {
|
|
1588
|
-
logger_default.debug("Sending batch of telemetry metrics", data);
|
|
1589
|
-
await TelemetryService.sendMetric(data);
|
|
1590
|
-
});
|
|
1591
|
-
setup(metadata) {
|
|
1592
|
-
this.telemetryMetadata = metadata;
|
|
1593
|
-
this.isTelemetryDisabled = false;
|
|
1594
|
-
this.telemetrySource = {
|
|
1595
|
-
host: this.telemetryMetadata?.host ?? this.telemetrySourceName,
|
|
1596
|
-
service: this.telemetryServiceName,
|
|
1597
|
-
language: this.telemetryLanguage,
|
|
1598
|
-
version: this.telemetryMetadata?.version,
|
|
1599
|
-
platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
|
|
1600
|
-
environment: getEnvVariable("NODE_ENV", "production")
|
|
1601
|
-
};
|
|
1602
|
-
this.sendMetric([{
|
|
1603
|
-
functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
|
|
1604
|
-
durationMs: 0,
|
|
1605
|
-
timestamp: Date.now() / 1e3,
|
|
1606
|
-
props: {},
|
|
1607
|
-
source: this.telemetrySource,
|
|
1608
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1609
|
-
error: void 0
|
|
1610
|
-
}]);
|
|
1611
|
-
}
|
|
1612
|
-
/**
|
|
1613
|
-
* Instrument the telemetry for the given instance.
|
|
1614
|
-
*
|
|
1615
|
-
* You can pass the instance and the file name of the instance to instrument the telemetry.
|
|
1616
|
-
* This will instrument all the methods of the instance and log the telemetry for each method call.
|
|
1617
|
-
* @param instance - any instance that extends InstrumentedInstance
|
|
1618
|
-
* @param fileName - the file name of the instance
|
|
1619
|
-
* @returns
|
|
1620
|
-
*/
|
|
1621
|
-
instrument(instance, fileName) {
|
|
1622
|
-
const proto = Object.getPrototypeOf(instance);
|
|
1623
|
-
const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
|
|
1624
|
-
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
1625
|
-
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
1626
|
-
});
|
|
1627
|
-
const instrumentedClassName = fileName ?? instance.constructor?.name ?? "unknown";
|
|
1628
|
-
for (const name of methodNames) {
|
|
1629
|
-
const originalMethod = instance[name];
|
|
1630
|
-
instance[name] = async (...args) => {
|
|
1631
|
-
const telemetryEnabled = this.shouldSendTelemetry();
|
|
1632
|
-
const startTime = telemetryEnabled ? Date.now() : void 0;
|
|
1633
|
-
try {
|
|
1634
|
-
const result = await originalMethod.apply(instance, args);
|
|
1635
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1636
|
-
const durationMs = Date.now() - startTime;
|
|
1637
|
-
const telemetryPayload = {
|
|
1638
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1639
|
-
durationMs,
|
|
1640
|
-
timestamp: startTime / 1e3,
|
|
1641
|
-
props: {
|
|
1642
|
-
fileName: instrumentedClassName,
|
|
1643
|
-
method: name,
|
|
1644
|
-
params: args
|
|
1645
|
-
},
|
|
1646
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1647
|
-
error: void 0,
|
|
1648
|
-
source: this.telemetrySource
|
|
1649
|
-
};
|
|
1650
|
-
this.batchProcessor.pushItem(telemetryPayload);
|
|
1651
|
-
}
|
|
1652
|
-
return result;
|
|
1653
|
-
} catch (error) {
|
|
1654
|
-
if (error instanceof Error) {
|
|
1655
|
-
if (!error.errorId) {
|
|
1656
|
-
error.errorId = getRandomUUID();
|
|
1657
|
-
if (telemetryEnabled && startTime !== void 0) {
|
|
1658
|
-
const durationMs = Date.now() - startTime;
|
|
1659
|
-
await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs);
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
throw error;
|
|
1664
|
-
}
|
|
1665
|
-
};
|
|
1666
|
-
}
|
|
1667
|
-
return instance;
|
|
1668
|
-
}
|
|
1669
|
-
/**
|
|
1670
|
-
* Check if the telemetry should be sent.
|
|
1671
|
-
* @returns true if the telemetry should be sent, false otherwise
|
|
1672
|
-
*/
|
|
1673
|
-
shouldSendTelemetry() {
|
|
1674
|
-
const telemetryDisabledEnvironments = ["test", "ci"];
|
|
1675
|
-
const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
|
|
1676
|
-
const isDisabledEnvironment = telemetryDisabledEnvironments.includes(nodeEnv);
|
|
1677
|
-
const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
|
|
1678
|
-
return !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDisabledEnvironment;
|
|
1679
|
-
}
|
|
1680
|
-
/**
|
|
1681
|
-
* Prepare and send the error telemetry.
|
|
1682
|
-
*
|
|
1683
|
-
* @TODO This currently blocks the thread and sends the telemetry to the server.
|
|
1684
|
-
*
|
|
1685
|
-
* @param {unknown} error - The error to send.
|
|
1686
|
-
* @param {string} instrumentedClassName - The class name of the instrumented class.
|
|
1687
|
-
* @param {string} name - The name of the method that threw the error.
|
|
1688
|
-
* @param {unknown[]} args - The arguments passed to the method.
|
|
1689
|
-
* @param {number} startTime - The start time of the method invocation in milliseconds.
|
|
1690
|
-
* @param {number} durationMs - The duration of the method invocation in milliseconds.
|
|
1691
|
-
*/
|
|
1692
|
-
async prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs) {
|
|
1693
|
-
const telemetryPayload = {
|
|
1694
|
-
functionName: `${instrumentedClassName}.${name}`,
|
|
1695
|
-
durationMs,
|
|
1696
|
-
timestamp: startTime / 1e3,
|
|
1697
|
-
props: {
|
|
1698
|
-
fileName: instrumentedClassName,
|
|
1699
|
-
method: name,
|
|
1700
|
-
params: args
|
|
1701
|
-
},
|
|
1702
|
-
metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
|
|
1703
|
-
source: this.telemetrySource
|
|
1704
|
-
};
|
|
1705
|
-
if (error instanceof ComposioError$1) telemetryPayload.error = {
|
|
1706
|
-
errorId: error.errorId,
|
|
1707
|
-
name: error.name,
|
|
1708
|
-
message: error.message,
|
|
1709
|
-
stack: error.stack
|
|
1710
|
-
};
|
|
1711
|
-
else if (error instanceof ComposioError) telemetryPayload.error = {
|
|
1712
|
-
errorId: error.errorId,
|
|
1713
|
-
name: error.name,
|
|
1714
|
-
code: error.code,
|
|
1715
|
-
message: error.message,
|
|
1716
|
-
stack: error.stack
|
|
1717
|
-
};
|
|
1718
|
-
else if (error instanceof Error) telemetryPayload.error = {
|
|
1719
|
-
errorId: error.errorId,
|
|
1720
|
-
name: error.name ?? "Unknown error",
|
|
1721
|
-
message: error.message,
|
|
1722
|
-
stack: error.stack
|
|
1723
|
-
};
|
|
1724
|
-
await this.sendErrorTelemetry(telemetryPayload);
|
|
1725
|
-
}
|
|
1726
|
-
/**
|
|
1727
|
-
* Send the telemetry payload to the server.
|
|
1728
|
-
* @param payload - the telemetry payload to send
|
|
1729
|
-
* @returns
|
|
1730
|
-
*/
|
|
1731
|
-
async sendMetric(payload) {
|
|
1732
|
-
if (!this.shouldSendTelemetry()) {
|
|
1733
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1734
|
-
return;
|
|
1735
|
-
}
|
|
1736
|
-
try {
|
|
1737
|
-
logger_default.debug("SDK Metric", payload);
|
|
1738
|
-
await TelemetryService.sendMetric(payload);
|
|
1739
|
-
} catch (error) {
|
|
1740
|
-
logger_default.error("Error sending metric telemetry", error);
|
|
1741
|
-
}
|
|
1742
|
-
}
|
|
1743
|
-
async sendErrorTelemetry(payload) {
|
|
1744
|
-
if (!this.shouldSendTelemetry()) {
|
|
1745
|
-
logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
|
|
1746
|
-
return;
|
|
1747
|
-
}
|
|
1748
|
-
try {
|
|
1749
|
-
logger_default.debug("SDK Error Telemetry", payload);
|
|
1750
|
-
await TelemetryService.sendErrorLog(payload);
|
|
1751
|
-
} catch (error) {
|
|
1752
|
-
logger_default.error("Error sending error telemetry", error);
|
|
1753
|
-
}
|
|
1754
|
-
}
|
|
1755
|
-
};
|
|
1756
|
-
const telemetry = new TelemetryTransport();
|
|
1757
|
-
|
|
1758
1129
|
//#endregion
|
|
1759
1130
|
//#region src/errors/AuthConfigErrors.ts
|
|
1760
1131
|
const AuthConfigErrorCodes = { AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND" };
|
|
@@ -2359,220 +1730,6 @@ var ComposioFileUploadError = class extends ComposioError {
|
|
|
2359
1730
|
}
|
|
2360
1731
|
};
|
|
2361
1732
|
|
|
2362
|
-
//#endregion
|
|
2363
|
-
//#region src/utils/fileUtils.ts
|
|
2364
|
-
const getExtensionFromMimeType = (mimeType) => {
|
|
2365
|
-
const mimeToExt = {
|
|
2366
|
-
"text/plain": "txt",
|
|
2367
|
-
"text/html": "html",
|
|
2368
|
-
"text/css": "css",
|
|
2369
|
-
"text/javascript": "js",
|
|
2370
|
-
"application/json": "json",
|
|
2371
|
-
"application/xml": "xml",
|
|
2372
|
-
"application/pdf": "pdf",
|
|
2373
|
-
"application/zip": "zip",
|
|
2374
|
-
"application/x-zip-compressed": "zip",
|
|
2375
|
-
"application/gzip": "gz",
|
|
2376
|
-
"application/x-tar": "tar",
|
|
2377
|
-
"application/msword": "doc",
|
|
2378
|
-
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
2379
|
-
"application/vnd.ms-excel": "xls",
|
|
2380
|
-
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
2381
|
-
"application/vnd.ms-powerpoint": "ppt",
|
|
2382
|
-
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
|
|
2383
|
-
"image/jpeg": "jpg",
|
|
2384
|
-
"image/jpg": "jpg",
|
|
2385
|
-
"image/png": "png",
|
|
2386
|
-
"image/gif": "gif",
|
|
2387
|
-
"image/svg+xml": "svg",
|
|
2388
|
-
"image/webp": "webp",
|
|
2389
|
-
"image/bmp": "bmp",
|
|
2390
|
-
"image/tiff": "tiff",
|
|
2391
|
-
"audio/mpeg": "mp3",
|
|
2392
|
-
"audio/wav": "wav",
|
|
2393
|
-
"audio/ogg": "ogg",
|
|
2394
|
-
"video/mp4": "mp4",
|
|
2395
|
-
"video/mpeg": "mpeg",
|
|
2396
|
-
"video/quicktime": "mov",
|
|
2397
|
-
"video/x-msvideo": "avi",
|
|
2398
|
-
"video/webm": "webm"
|
|
2399
|
-
};
|
|
2400
|
-
const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
|
|
2401
|
-
if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
|
|
2402
|
-
const parts = cleanMimeType.split("/");
|
|
2403
|
-
if (parts.length === 2) {
|
|
2404
|
-
const cleanSubtype = parts[1].toLowerCase();
|
|
2405
|
-
if (cleanSubtype.includes("+")) {
|
|
2406
|
-
const plusParts = cleanSubtype.split("+");
|
|
2407
|
-
const prefix = plusParts[0];
|
|
2408
|
-
const suffix = plusParts[plusParts.length - 1];
|
|
2409
|
-
if ([
|
|
2410
|
-
"svg",
|
|
2411
|
-
"atom",
|
|
2412
|
-
"rss"
|
|
2413
|
-
].includes(prefix)) return prefix;
|
|
2414
|
-
if ([
|
|
2415
|
-
"json",
|
|
2416
|
-
"xml",
|
|
2417
|
-
"yaml",
|
|
2418
|
-
"zip",
|
|
2419
|
-
"gzip"
|
|
2420
|
-
].includes(suffix)) return suffix;
|
|
2421
|
-
return suffix;
|
|
2422
|
-
}
|
|
2423
|
-
return cleanSubtype || "txt";
|
|
2424
|
-
}
|
|
2425
|
-
return "txt";
|
|
2426
|
-
};
|
|
2427
|
-
const generateTimestampedFilename = (extension, prefix) => {
|
|
2428
|
-
return `${prefix || "file_ts"}${Date.now()}${getRandomShortId()}.${extension}`;
|
|
2429
|
-
};
|
|
2430
|
-
const readFileContent = async (path) => {
|
|
2431
|
-
try {
|
|
2432
|
-
const content = __require("fs").readFileSync(path);
|
|
2433
|
-
return {
|
|
2434
|
-
fileName: generateTimestampedFilename(path.split(".").pop() || "txt"),
|
|
2435
|
-
content: content.toString("base64"),
|
|
2436
|
-
mimeType: "application/octet-stream"
|
|
2437
|
-
};
|
|
2438
|
-
} catch (error) {
|
|
2439
|
-
throw new Error(`Error reading file at ${path}: ${error}`);
|
|
2440
|
-
}
|
|
2441
|
-
};
|
|
2442
|
-
const readFileContentFromURL = async (path) => {
|
|
2443
|
-
const response = await fetch(path);
|
|
2444
|
-
if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
|
|
2445
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
2446
|
-
const content = Buffer.from(arrayBuffer);
|
|
2447
|
-
const mimeType = response.headers.get("content-type") || "application/octet-stream";
|
|
2448
|
-
const pathname = new URL(path).pathname;
|
|
2449
|
-
let fileName = pathModule.basename(pathname);
|
|
2450
|
-
if (!fileName || fileName === "/") fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2451
|
-
else if (!fileName.includes(".")) fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
|
|
2452
|
-
return {
|
|
2453
|
-
content: content.toString("base64"),
|
|
2454
|
-
mimeType,
|
|
2455
|
-
fileName
|
|
2456
|
-
};
|
|
2457
|
-
};
|
|
2458
|
-
const uploadFileToS3 = async (fileName, content, toolSlug, toolkitSlug, mimeType, client) => {
|
|
2459
|
-
const response = await client.files.createPresignedURL({
|
|
2460
|
-
filename: fileName,
|
|
2461
|
-
mimetype: mimeType,
|
|
2462
|
-
md5: crypto.createHash("md5").update(Buffer.from(content, "base64")).digest("hex"),
|
|
2463
|
-
tool_slug: toolSlug,
|
|
2464
|
-
toolkit_slug: toolkitSlug
|
|
2465
|
-
});
|
|
2466
|
-
const { key, type } = response;
|
|
2467
|
-
if (type === "new" || type === "update") {
|
|
2468
|
-
logger_default.debug(`Uploading ${key} file to S3: ${key}`);
|
|
2469
|
-
const buffer = Buffer.from(content, "base64");
|
|
2470
|
-
const signedURL = response.type === "update" ? response.update_presigned_url : response.new_presigned_url;
|
|
2471
|
-
const uploadResponse = await fetch(signedURL, {
|
|
2472
|
-
method: "PUT",
|
|
2473
|
-
body: buffer,
|
|
2474
|
-
headers: {
|
|
2475
|
-
"Content-Type": mimeType,
|
|
2476
|
-
"Content-Length": buffer.length.toString()
|
|
2477
|
-
}
|
|
2478
|
-
});
|
|
2479
|
-
if (!uploadResponse.ok) throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
|
|
2480
|
-
} else logger_default.debug(`File already exists in S3: ${key}`);
|
|
2481
|
-
return key;
|
|
2482
|
-
};
|
|
2483
|
-
const readFile = async (file) => {
|
|
2484
|
-
if (file instanceof File) {
|
|
2485
|
-
const content = await file.arrayBuffer();
|
|
2486
|
-
return {
|
|
2487
|
-
fileName: file.name,
|
|
2488
|
-
content: Buffer.from(content).toString("base64"),
|
|
2489
|
-
mimeType: file.type
|
|
2490
|
-
};
|
|
2491
|
-
} else if (typeof file === "string") if (file.startsWith("http")) return await readFileContentFromURL(file);
|
|
2492
|
-
else return await readFileContent(file);
|
|
2493
|
-
throw new Error("Invalid file type");
|
|
2494
|
-
};
|
|
2495
|
-
const getFileDataAfterUploadingToS3 = async (file, { toolSlug, toolkitSlug, client }) => {
|
|
2496
|
-
if (!file) throw new Error("Either path or blob must be provided");
|
|
2497
|
-
const fileData = await readFile(file);
|
|
2498
|
-
logger_default.debug(`Uploading file to S3...`);
|
|
2499
|
-
const s3key = await uploadFileToS3(pathModule.basename(fileData.fileName), fileData.content, toolSlug, toolkitSlug, fileData.mimeType, client);
|
|
2500
|
-
logger_default.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
|
|
2501
|
-
return {
|
|
2502
|
-
name: fileData.fileName,
|
|
2503
|
-
mimetype: fileData.mimeType,
|
|
2504
|
-
s3key
|
|
2505
|
-
};
|
|
2506
|
-
};
|
|
2507
|
-
const downloadFileFromS3 = async ({ toolSlug, s3Url, mimeType }) => {
|
|
2508
|
-
const response = await fetch(s3Url);
|
|
2509
|
-
if (!response.ok) throw new Error(`Failed to download file: ${response.statusText}`);
|
|
2510
|
-
const data = await response.arrayBuffer();
|
|
2511
|
-
const fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType), `${toolSlug}_`);
|
|
2512
|
-
return {
|
|
2513
|
-
name: fileName,
|
|
2514
|
-
mimeType,
|
|
2515
|
-
s3Url,
|
|
2516
|
-
filePath: saveFile(fileName, Buffer.from(data), true)
|
|
2517
|
-
};
|
|
2518
|
-
};
|
|
2519
|
-
/**
|
|
2520
|
-
* Gets the Composio directory.
|
|
2521
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2522
|
-
* @returns The path to the Composio directory.
|
|
2523
|
-
*/
|
|
2524
|
-
const getComposioDir = (createDirIfNotExists = false) => {
|
|
2525
|
-
try {
|
|
2526
|
-
const os = __require("os");
|
|
2527
|
-
const path = __require("path");
|
|
2528
|
-
const fs = __require("fs");
|
|
2529
|
-
const composioDir = path.join(os.homedir(), COMPOSIO_DIR);
|
|
2530
|
-
if (createDirIfNotExists && !fs.existsSync(composioDir)) fs.mkdirSync(composioDir, { recursive: true });
|
|
2531
|
-
return composioDir;
|
|
2532
|
-
} catch (_error) {
|
|
2533
|
-
return null;
|
|
2534
|
-
}
|
|
2535
|
-
};
|
|
2536
|
-
/**
|
|
2537
|
-
* Gets the Composio temporary files directory.
|
|
2538
|
-
* @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
|
|
2539
|
-
* @returns The path to the Composio temporary files directory.
|
|
2540
|
-
*/
|
|
2541
|
-
const getComposioTempFilesDir = (createDirIfNotExists = false) => {
|
|
2542
|
-
try {
|
|
2543
|
-
const os = __require("os");
|
|
2544
|
-
const path = __require("path");
|
|
2545
|
-
const fs = __require("fs");
|
|
2546
|
-
const composioFilesDir = path.join(os.homedir(), COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
|
|
2547
|
-
if (createDirIfNotExists && !fs.existsSync(composioFilesDir)) fs.mkdirSync(composioFilesDir, { recursive: true });
|
|
2548
|
-
return composioFilesDir;
|
|
2549
|
-
} catch (_error) {
|
|
2550
|
-
return null;
|
|
2551
|
-
}
|
|
2552
|
-
};
|
|
2553
|
-
/**
|
|
2554
|
-
* Saves a file to the Composio directory.
|
|
2555
|
-
* @param file - The name of the file to save.
|
|
2556
|
-
* @param content - The content of the file to save. Can be a string or Buffer.
|
|
2557
|
-
* @param isTempFile - Whether the file is a temporary file.
|
|
2558
|
-
* @returns The path to the saved file.
|
|
2559
|
-
*/
|
|
2560
|
-
const saveFile = (file, content, isTempFile = false) => {
|
|
2561
|
-
try {
|
|
2562
|
-
const path = __require("path");
|
|
2563
|
-
const fs = __require("fs");
|
|
2564
|
-
const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
|
|
2565
|
-
const filePath = path.join(composioFilesDir, path.basename(file));
|
|
2566
|
-
logger_default.info(`Saving file to: ${filePath}`);
|
|
2567
|
-
if (Buffer.isBuffer(content)) fs.writeFileSync(filePath, content);
|
|
2568
|
-
else fs.writeFileSync(filePath, content, "utf8");
|
|
2569
|
-
return filePath;
|
|
2570
|
-
} catch (_error) {
|
|
2571
|
-
logger_default.debug(`Error saving file: ${_error}`);
|
|
2572
|
-
return null;
|
|
2573
|
-
}
|
|
2574
|
-
};
|
|
2575
|
-
|
|
2576
1733
|
//#endregion
|
|
2577
1734
|
//#region src/utils/modifiers/FileToolModifier.ts
|
|
2578
1735
|
/**
|
|
@@ -4658,12 +3815,66 @@ const TriggersTypeListResponseSchema = z$1.object({
|
|
|
4658
3815
|
totalPages: z$1.number()
|
|
4659
3816
|
});
|
|
4660
3817
|
/**
|
|
3818
|
+
* Webhook payload schemas for V1, V2, V3 versions
|
|
3819
|
+
* These schemas represent the raw payload structure sent by Composio's webhook system
|
|
3820
|
+
*/
|
|
3821
|
+
/** V1 webhook payload - legacy format */
|
|
3822
|
+
const WebhookPayloadV1Schema = z$1.object({
|
|
3823
|
+
trigger_name: z$1.string(),
|
|
3824
|
+
connection_id: z$1.string(),
|
|
3825
|
+
trigger_id: z$1.string(),
|
|
3826
|
+
payload: z$1.record(z$1.unknown()),
|
|
3827
|
+
log_id: z$1.string()
|
|
3828
|
+
});
|
|
3829
|
+
/** V2 webhook payload - includes timestamp and nested data */
|
|
3830
|
+
const WebhookPayloadV2Schema = z$1.object({
|
|
3831
|
+
type: z$1.string(),
|
|
3832
|
+
timestamp: z$1.string(),
|
|
3833
|
+
log_id: z$1.string(),
|
|
3834
|
+
data: z$1.object({
|
|
3835
|
+
connection_id: z$1.string(),
|
|
3836
|
+
connection_nano_id: z$1.string(),
|
|
3837
|
+
trigger_nano_id: z$1.string(),
|
|
3838
|
+
trigger_id: z$1.string(),
|
|
3839
|
+
user_id: z$1.string()
|
|
3840
|
+
}).passthrough()
|
|
3841
|
+
});
|
|
3842
|
+
/** V3 webhook payload - current format with metadata */
|
|
3843
|
+
const WebhookPayloadV3Schema = z$1.object({
|
|
3844
|
+
id: z$1.string(),
|
|
3845
|
+
timestamp: z$1.string(),
|
|
3846
|
+
type: z$1.literal("composio.trigger.message"),
|
|
3847
|
+
metadata: z$1.object({
|
|
3848
|
+
log_id: z$1.string(),
|
|
3849
|
+
trigger_slug: z$1.string(),
|
|
3850
|
+
trigger_id: z$1.string(),
|
|
3851
|
+
connected_account_id: z$1.string(),
|
|
3852
|
+
auth_config_id: z$1.string(),
|
|
3853
|
+
user_id: z$1.string()
|
|
3854
|
+
}),
|
|
3855
|
+
data: z$1.record(z$1.unknown())
|
|
3856
|
+
});
|
|
3857
|
+
/** Union of all webhook payload versions */
|
|
3858
|
+
const WebhookPayloadSchema = z$1.union([
|
|
3859
|
+
WebhookPayloadV3Schema,
|
|
3860
|
+
WebhookPayloadV2Schema,
|
|
3861
|
+
WebhookPayloadV1Schema
|
|
3862
|
+
]);
|
|
3863
|
+
/** Webhook version enum */
|
|
3864
|
+
const WebhookVersions = {
|
|
3865
|
+
V1: "V1",
|
|
3866
|
+
V2: "V2",
|
|
3867
|
+
V3: "V3"
|
|
3868
|
+
};
|
|
3869
|
+
/**
|
|
4661
3870
|
* Parameters for verifying a webhook signature
|
|
4662
3871
|
*/
|
|
4663
3872
|
const VerifyWebhookParamsSchema = z$1.object({
|
|
3873
|
+
id: z$1.string(),
|
|
4664
3874
|
payload: z$1.string(),
|
|
4665
|
-
signature: z$1.string(),
|
|
4666
3875
|
secret: z$1.string(),
|
|
3876
|
+
signature: z$1.string(),
|
|
3877
|
+
timestamp: z$1.string(),
|
|
4667
3878
|
tolerance: z$1.number().optional().default(300)
|
|
4668
3879
|
});
|
|
4669
3880
|
|
|
@@ -5195,15 +4406,20 @@ var Triggers = class {
|
|
|
5195
4406
|
* Verify an incoming webhook payload and signature.
|
|
5196
4407
|
*
|
|
5197
4408
|
* This method validates that the webhook request is authentic by:
|
|
5198
|
-
* 1. Verifying the HMAC-SHA256 signature matches the payload
|
|
4409
|
+
* 1. Verifying the HMAC-SHA256 signature matches the payload using the correct signing format
|
|
5199
4410
|
* 2. Optionally checking that the webhook timestamp is within the tolerance window
|
|
5200
4411
|
*
|
|
4412
|
+
* The signature is computed as: `HMAC-SHA256(${webhookId}.${webhookTimestamp}.${payload}, secret)`
|
|
4413
|
+
* and is expected in the format: `v1,base64EncodedSignature`
|
|
4414
|
+
*
|
|
5201
4415
|
* @param {VerifyWebhookParams} params - The verification parameters
|
|
5202
4416
|
* @param {string} params.payload - The raw webhook payload as a string (request body)
|
|
5203
|
-
* @param {string} params.signature - The signature from the webhook
|
|
4417
|
+
* @param {string} params.signature - The signature from the 'webhook-signature' header
|
|
5204
4418
|
* @param {string} params.secret - The webhook secret used to sign the payload
|
|
4419
|
+
* @param {string} params.webhookId - The webhook ID from the 'webhook-id' header
|
|
4420
|
+
* @param {string} params.webhookTimestamp - The timestamp from the 'webhook-timestamp' header (Unix seconds)
|
|
5205
4421
|
* @param {number} [params.tolerance=300] - Maximum allowed age of the webhook in seconds (default: 5 minutes). Set to 0 to disable timestamp validation.
|
|
5206
|
-
* @returns {VerifyWebhookResult} The verified and parsed webhook payload
|
|
4422
|
+
* @returns {VerifyWebhookResult} The verified and parsed webhook payload with version information
|
|
5207
4423
|
*
|
|
5208
4424
|
* @throws {ValidationError} If the parameters are invalid
|
|
5209
4425
|
* @throws {ComposioWebhookSignatureVerificationError} If the signature verification fails
|
|
@@ -5214,14 +4430,17 @@ var Triggers = class {
|
|
|
5214
4430
|
* // In an Express.js webhook handler
|
|
5215
4431
|
* app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
|
|
5216
4432
|
* try {
|
|
5217
|
-
* const
|
|
4433
|
+
* const result = composio.triggers.verifyWebhook({
|
|
5218
4434
|
* payload: req.body.toString(),
|
|
5219
|
-
* signature: req.headers['
|
|
4435
|
+
* signature: req.headers['webhook-signature'] as string,
|
|
4436
|
+
* webhookId: req.headers['webhook-id'] as string,
|
|
4437
|
+
* webhookTimestamp: req.headers['webhook-timestamp'] as string,
|
|
5220
4438
|
* secret: process.env.COMPOSIO_WEBHOOK_SECRET!,
|
|
5221
4439
|
* });
|
|
5222
4440
|
*
|
|
5223
4441
|
* // Process the verified payload
|
|
5224
|
-
* console.log('
|
|
4442
|
+
* console.log('Webhook version:', result.version);
|
|
4443
|
+
* console.log('Received trigger:', result.payload.triggerSlug);
|
|
5225
4444
|
* res.status(200).send('OK');
|
|
5226
4445
|
* } catch (error) {
|
|
5227
4446
|
* console.error('Webhook verification failed:', error);
|
|
@@ -5233,45 +4452,190 @@ var Triggers = class {
|
|
|
5233
4452
|
verifyWebhook(params) {
|
|
5234
4453
|
const parsedParams = VerifyWebhookParamsSchema.safeParse(params);
|
|
5235
4454
|
if (!parsedParams.success) throw new ValidationError("Invalid parameters passed to verifyWebhook", { cause: parsedParams.error });
|
|
5236
|
-
const { payload, signature, secret, tolerance } = parsedParams.data;
|
|
5237
|
-
this.
|
|
5238
|
-
|
|
4455
|
+
const { payload, signature, secret, id: webhookId, timestamp: webhookTimestamp, tolerance } = parsedParams.data;
|
|
4456
|
+
if (tolerance > 0) this.validateWebhookTimestamp(webhookTimestamp, tolerance);
|
|
4457
|
+
this.verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret);
|
|
4458
|
+
const { version: version$1, rawPayload, normalizedPayload } = this.parseWebhookPayload(payload);
|
|
4459
|
+
return {
|
|
4460
|
+
version: version$1,
|
|
4461
|
+
payload: normalizedPayload,
|
|
4462
|
+
rawPayload
|
|
4463
|
+
};
|
|
4464
|
+
}
|
|
4465
|
+
/**
|
|
4466
|
+
* Parses the webhook payload and detects its version (V1, V2, or V3)
|
|
4467
|
+
* @private
|
|
4468
|
+
*/
|
|
4469
|
+
parseWebhookPayload(payload) {
|
|
4470
|
+
let jsonPayload;
|
|
5239
4471
|
try {
|
|
5240
|
-
|
|
4472
|
+
jsonPayload = JSON.parse(payload);
|
|
5241
4473
|
} catch (error) {
|
|
5242
4474
|
throw new ComposioWebhookPayloadError("Failed to parse webhook payload as JSON", { cause: error });
|
|
5243
4475
|
}
|
|
5244
|
-
const
|
|
5245
|
-
if (
|
|
5246
|
-
|
|
4476
|
+
const v3Result = WebhookPayloadV3Schema.safeParse(jsonPayload);
|
|
4477
|
+
if (v3Result.success) return {
|
|
4478
|
+
version: WebhookVersions.V3,
|
|
4479
|
+
rawPayload: v3Result.data,
|
|
4480
|
+
normalizedPayload: this.normalizeV3Payload(v3Result.data)
|
|
4481
|
+
};
|
|
4482
|
+
const v2Result = WebhookPayloadV2Schema.safeParse(jsonPayload);
|
|
4483
|
+
if (v2Result.success) return {
|
|
4484
|
+
version: WebhookVersions.V2,
|
|
4485
|
+
rawPayload: v2Result.data,
|
|
4486
|
+
normalizedPayload: this.normalizeV2Payload(v2Result.data)
|
|
4487
|
+
};
|
|
4488
|
+
const v1Result = WebhookPayloadV1Schema.safeParse(jsonPayload);
|
|
4489
|
+
if (v1Result.success) return {
|
|
4490
|
+
version: WebhookVersions.V1,
|
|
4491
|
+
rawPayload: v1Result.data,
|
|
4492
|
+
normalizedPayload: this.normalizeV1Payload(v1Result.data)
|
|
4493
|
+
};
|
|
4494
|
+
throw new ComposioWebhookPayloadError("Webhook payload does not match any known version (V1, V2, or V3). Please ensure you are using a supported webhook payload format.", { cause: {
|
|
4495
|
+
v1Error: v1Result.error?.message,
|
|
4496
|
+
v2Error: v2Result.error?.message,
|
|
4497
|
+
v3Error: v3Result.error?.message
|
|
4498
|
+
} });
|
|
4499
|
+
}
|
|
4500
|
+
/**
|
|
4501
|
+
* Normalizes a V1 webhook payload to IncomingTriggerPayload format
|
|
4502
|
+
* @private
|
|
4503
|
+
*/
|
|
4504
|
+
normalizeV1Payload(payload) {
|
|
4505
|
+
const triggerName = payload.trigger_name;
|
|
4506
|
+
const toolkitSlug = triggerName.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4507
|
+
return {
|
|
4508
|
+
id: payload.trigger_id,
|
|
4509
|
+
uuid: payload.trigger_id,
|
|
4510
|
+
triggerSlug: triggerName,
|
|
4511
|
+
toolkitSlug,
|
|
4512
|
+
userId: "",
|
|
4513
|
+
payload: payload.payload,
|
|
4514
|
+
originalPayload: payload.payload,
|
|
4515
|
+
metadata: {
|
|
4516
|
+
id: payload.trigger_id,
|
|
4517
|
+
uuid: payload.trigger_id,
|
|
4518
|
+
toolkitSlug,
|
|
4519
|
+
triggerSlug: triggerName,
|
|
4520
|
+
triggerConfig: {},
|
|
4521
|
+
connectedAccount: {
|
|
4522
|
+
id: payload.connection_id,
|
|
4523
|
+
uuid: payload.connection_id,
|
|
4524
|
+
authConfigId: "",
|
|
4525
|
+
authConfigUUID: "",
|
|
4526
|
+
userId: "",
|
|
4527
|
+
status: "ACTIVE"
|
|
4528
|
+
}
|
|
4529
|
+
}
|
|
4530
|
+
};
|
|
5247
4531
|
}
|
|
5248
4532
|
/**
|
|
5249
|
-
*
|
|
4533
|
+
* Normalizes a V2 webhook payload to IncomingTriggerPayload format
|
|
5250
4534
|
* @private
|
|
5251
4535
|
*/
|
|
5252
|
-
|
|
4536
|
+
normalizeV2Payload(payload) {
|
|
4537
|
+
const triggerSlug = payload.type.toUpperCase();
|
|
4538
|
+
const toolkitSlug = triggerSlug.split("_")[0] || "UNKNOWN";
|
|
4539
|
+
const { connection_id, connection_nano_id, trigger_nano_id, trigger_id, user_id, ...restData } = payload.data;
|
|
4540
|
+
return {
|
|
4541
|
+
id: trigger_nano_id,
|
|
4542
|
+
uuid: trigger_id,
|
|
4543
|
+
triggerSlug,
|
|
4544
|
+
toolkitSlug,
|
|
4545
|
+
userId: user_id,
|
|
4546
|
+
payload: restData,
|
|
4547
|
+
originalPayload: restData,
|
|
4548
|
+
metadata: {
|
|
4549
|
+
id: trigger_nano_id,
|
|
4550
|
+
uuid: trigger_id,
|
|
4551
|
+
toolkitSlug,
|
|
4552
|
+
triggerSlug,
|
|
4553
|
+
triggerConfig: {},
|
|
4554
|
+
connectedAccount: {
|
|
4555
|
+
id: connection_nano_id,
|
|
4556
|
+
uuid: connection_id,
|
|
4557
|
+
authConfigId: "",
|
|
4558
|
+
authConfigUUID: "",
|
|
4559
|
+
userId: user_id,
|
|
4560
|
+
status: "ACTIVE"
|
|
4561
|
+
}
|
|
4562
|
+
}
|
|
4563
|
+
};
|
|
4564
|
+
}
|
|
4565
|
+
/**
|
|
4566
|
+
* Normalizes a V3 webhook payload to IncomingTriggerPayload format
|
|
4567
|
+
* @private
|
|
4568
|
+
*/
|
|
4569
|
+
normalizeV3Payload(payload) {
|
|
4570
|
+
const triggerSlug = payload.metadata.trigger_slug;
|
|
4571
|
+
const toolkitSlug = triggerSlug.split("_")[0]?.toUpperCase() || "UNKNOWN";
|
|
4572
|
+
return {
|
|
4573
|
+
id: payload.metadata.trigger_id,
|
|
4574
|
+
uuid: payload.metadata.trigger_id,
|
|
4575
|
+
triggerSlug,
|
|
4576
|
+
toolkitSlug,
|
|
4577
|
+
userId: payload.metadata.user_id,
|
|
4578
|
+
payload: payload.data,
|
|
4579
|
+
originalPayload: payload.data,
|
|
4580
|
+
metadata: {
|
|
4581
|
+
id: payload.metadata.trigger_id,
|
|
4582
|
+
uuid: payload.metadata.trigger_id,
|
|
4583
|
+
toolkitSlug,
|
|
4584
|
+
triggerSlug,
|
|
4585
|
+
triggerConfig: {},
|
|
4586
|
+
connectedAccount: {
|
|
4587
|
+
id: payload.metadata.connected_account_id,
|
|
4588
|
+
uuid: payload.metadata.connected_account_id,
|
|
4589
|
+
authConfigId: payload.metadata.auth_config_id,
|
|
4590
|
+
authConfigUUID: payload.metadata.auth_config_id,
|
|
4591
|
+
userId: payload.metadata.user_id,
|
|
4592
|
+
status: "ACTIVE"
|
|
4593
|
+
}
|
|
4594
|
+
}
|
|
4595
|
+
};
|
|
4596
|
+
}
|
|
4597
|
+
/**
|
|
4598
|
+
* Verifies the HMAC-SHA256 signature of a webhook payload.
|
|
4599
|
+
* The signature format used by Composio is: `v1,base64EncodedSignature`
|
|
4600
|
+
* The signing input is: `${msgId}.${timestamp}.${payload}`
|
|
4601
|
+
* @private
|
|
4602
|
+
*/
|
|
4603
|
+
verifyWebhookSignature(webhookId, webhookTimestamp, payload, signature, secret) {
|
|
5253
4604
|
if (payload.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook payload was provided.");
|
|
5254
|
-
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the webhook
|
|
4605
|
+
if (signature.length === 0) throw new ComposioWebhookSignatureVerificationError("No signature header value was provided. Please pass the value of the 'webhook-signature' header.");
|
|
5255
4606
|
if (secret.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook secret was provided. You can find your webhook secret in your Composio dashboard.");
|
|
5256
|
-
|
|
5257
|
-
|
|
5258
|
-
const
|
|
5259
|
-
|
|
4607
|
+
if (webhookId.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook ID was provided. Please pass the value of the 'webhook-id' header.");
|
|
4608
|
+
if (webhookTimestamp.length === 0) throw new ComposioWebhookSignatureVerificationError("No webhook timestamp was provided. Please pass the value of the 'webhook-timestamp' header.");
|
|
4609
|
+
const signatures = signature.split(" ");
|
|
4610
|
+
const v1Signatures = [];
|
|
4611
|
+
for (const sig of signatures) {
|
|
4612
|
+
const [version$1, value] = sig.split(",");
|
|
4613
|
+
if (version$1 === "v1" && value) v1Signatures.push(value);
|
|
4614
|
+
}
|
|
4615
|
+
if (v1Signatures.length === 0) throw new ComposioWebhookSignatureVerificationError("No valid v1 signature found in the webhook-signature header. Expected format: 'v1,base64EncodedSignature'");
|
|
4616
|
+
const toSign = `${webhookId}.${webhookTimestamp}.${payload}`;
|
|
4617
|
+
const expectedSignature = crypto$1.createHmac("sha256", secret).update(toSign, "utf8").digest("base64");
|
|
4618
|
+
let isValid = false;
|
|
4619
|
+
for (const providedSignature of v1Signatures) {
|
|
4620
|
+
const signatureBuffer = Buffer.from(providedSignature);
|
|
4621
|
+
const expectedBuffer = Buffer.from(expectedSignature);
|
|
4622
|
+
if (signatureBuffer.length === expectedBuffer.length && crypto$1.timingSafeEqual(signatureBuffer, expectedBuffer)) {
|
|
4623
|
+
isValid = true;
|
|
4624
|
+
break;
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
if (!isValid) throw new ComposioWebhookSignatureVerificationError("The signature provided is invalid. Please ensure you are using the correct webhook secret.");
|
|
5260
4628
|
}
|
|
5261
4629
|
/**
|
|
5262
4630
|
* Validates that the webhook timestamp is within the allowed tolerance
|
|
5263
4631
|
* @private
|
|
5264
4632
|
*/
|
|
5265
|
-
validateWebhookTimestamp(
|
|
5266
|
-
const
|
|
5267
|
-
if (
|
|
5268
|
-
|
|
5269
|
-
return;
|
|
5270
|
-
}
|
|
5271
|
-
const webhookTime = Date.parse(timestamp);
|
|
5272
|
-
if (Number.isNaN(webhookTime)) throw new ComposioWebhookPayloadError(`Invalid timestamp in webhook payload: ${timestamp}. Expected ISO 8601 format.`);
|
|
4633
|
+
validateWebhookTimestamp(webhookTimestamp, tolerance) {
|
|
4634
|
+
const timestampSeconds = parseInt(webhookTimestamp, 10);
|
|
4635
|
+
if (Number.isNaN(timestampSeconds)) throw new ComposioWebhookPayloadError(`Invalid webhook timestamp: ${webhookTimestamp}. Expected Unix timestamp in seconds.`);
|
|
4636
|
+
const webhookTimeMs = timestampSeconds * 1e3;
|
|
5273
4637
|
const currentTime = Date.now();
|
|
5274
|
-
const timeDifference = Math.abs(currentTime -
|
|
4638
|
+
const timeDifference = Math.abs(currentTime - webhookTimeMs);
|
|
5275
4639
|
if (timeDifference > tolerance * 1e3) throw new ComposioWebhookSignatureVerificationError(`The webhook timestamp is outside the allowed tolerance. The webhook was sent ${Math.round(timeDifference / 1e3)} seconds ago, but the maximum allowed age is ${tolerance} seconds.`);
|
|
5276
4640
|
}
|
|
5277
4641
|
};
|
|
@@ -5690,9 +5054,9 @@ var MCP = class {
|
|
|
5690
5054
|
//#region src/utils/sdk.ts
|
|
5691
5055
|
const userDataPath = () => {
|
|
5692
5056
|
try {
|
|
5693
|
-
const
|
|
5694
|
-
|
|
5695
|
-
return
|
|
5057
|
+
const homeDir = platform.homedir();
|
|
5058
|
+
if (!homeDir) return null;
|
|
5059
|
+
return platform.joinPath(homeDir, COMPOSIO_DIR, USER_DATA_FILE_NAME);
|
|
5696
5060
|
} catch (_error) {
|
|
5697
5061
|
logger_default.debug("Environment", `Unable to get user data path`);
|
|
5698
5062
|
return null;
|
|
@@ -5705,7 +5069,9 @@ const userDataPath = () => {
|
|
|
5705
5069
|
*/
|
|
5706
5070
|
const getUserDataJson = () => {
|
|
5707
5071
|
try {
|
|
5708
|
-
const
|
|
5072
|
+
const dataPath = userDataPath();
|
|
5073
|
+
if (!dataPath || !platform.supportsFileSystem) return {};
|
|
5074
|
+
const data = platform.readFileSync(dataPath, "utf8");
|
|
5709
5075
|
return JSON.parse(data);
|
|
5710
5076
|
} catch (_error) {
|
|
5711
5077
|
logger_default.debug("Environment", "No user data file found");
|
|
@@ -6255,42 +5621,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
6255
5621
|
|
|
6256
5622
|
//#endregion
|
|
6257
5623
|
//#region package.json
|
|
6258
|
-
var version = "0.
|
|
6259
|
-
|
|
6260
|
-
//#endregion
|
|
6261
|
-
//#region src/models/Files.ts
|
|
6262
|
-
var Files = class {
|
|
6263
|
-
constructor(client) {
|
|
6264
|
-
this.client = client;
|
|
6265
|
-
telemetry.instrument(this, "Files");
|
|
6266
|
-
}
|
|
6267
|
-
/**
|
|
6268
|
-
* Upload a file to S3 and return the file data.
|
|
6269
|
-
* @param filePath - The path to the file to upload or a URL of the file to upload.
|
|
6270
|
-
* @param toolSlug - The slug of the tool that is uploading the file.
|
|
6271
|
-
* @param toolkitSlug - The slug of the toolkit that is uploading the file.
|
|
6272
|
-
* @returns The file data.
|
|
6273
|
-
*/
|
|
6274
|
-
async upload({ file, toolSlug, toolkitSlug }) {
|
|
6275
|
-
return await getFileDataAfterUploadingToS3(file, {
|
|
6276
|
-
toolSlug,
|
|
6277
|
-
toolkitSlug,
|
|
6278
|
-
client: this.client
|
|
6279
|
-
});
|
|
6280
|
-
}
|
|
6281
|
-
/**
|
|
6282
|
-
* Download a file from S3 and return the file data.
|
|
6283
|
-
* @param s3key - The S3 key of the file to download.
|
|
6284
|
-
* @returns The file data.
|
|
6285
|
-
*/
|
|
6286
|
-
async download({ toolSlug, s3Url, mimeType }) {
|
|
6287
|
-
return await downloadFileFromS3({
|
|
6288
|
-
toolSlug,
|
|
6289
|
-
s3Url,
|
|
6290
|
-
mimeType
|
|
6291
|
-
});
|
|
6292
|
-
}
|
|
6293
|
-
};
|
|
5624
|
+
var version = "0.5.0";
|
|
6294
5625
|
|
|
6295
5626
|
//#endregion
|
|
6296
5627
|
//#region src/utils/session.ts
|
|
@@ -7330,4 +6661,4 @@ const ComposioMcpUpdateResponseSchema = z$1.object({
|
|
|
7330
6661
|
});
|
|
7331
6662
|
|
|
7332
6663
|
//#endregion
|
|
7333
|
-
export { AuthConfigCreationToolAccessConfigSchema, AuthConfigErrorCodes, AuthConfigListParamsSchema, AuthConfigListResponseSchema, AuthConfigRetrieveResponseSchema, AuthConfigToolAccessConfigSchema, AuthConfigTypes, AuthConfigUpdateParamsSchema, AuthCustomConfigUpdateParamsSchema, AuthDefaultConfigUpdateParamsSchema, AuthScheme, AuthSchemeEnum, AuthSchemeTypes, BaseAgenticProvider, BaseNonAgenticProvider, BillcomAuthConnectionDataSchema, Composio, ComposioAuthConfigNotFoundError, ComposioConnectedAccountNotFoundError, ComposioCustomCreateResponseSchema, ComposioCustomToolsNotInitializedError, ComposioError, ComposioFailedToCreateConnectedAccountLink, ComposioFailedToCreatePusherClientError, ComposioFailedToGetSDKRealtimeCredentialsError, ComposioFailedToSubscribeToPusherChannelError, ComposioFailedToUnsubscribeFromPusherChannelError, ComposioGenerateURLParamsSchema, ComposioGenerateURLResponseSchema, ComposioGlobalExecuteToolFnNotSetError, ComposioInvalidExecuteFunctionError, ComposioInvalidModifierError, ComposioMcpDeleteResponseSchema, ComposioMcpListResponseSchema, ComposioMcpRetrieveResponseSchema, ComposioMcpUpdateResponseSchema, ComposioMultipleConnectedAccountsError, ComposioNoAPIKeyError, ComposioProvider, ComposioProviderNotDefinedError, ComposioToolExecutionError, ComposioToolNotFoundError, ComposioToolVersionRequiredError, ComposioToolkitFetchError, ComposioToolkitNotFoundError, ComposioTriggerTypeNotFoundError, ComposioWebhookPayloadError, ComposioWebhookSignatureVerificationError, ConnectedAccountAuthConfigSchema, ConnectedAccountErrorCodes, ConnectedAccountListParamsSchema, ConnectedAccountListResponseSchema, ConnectedAccountRetrieveResponseSchema, ConnectedAccountStatusSchema, ConnectedAccountStatuses, ConnectionDataSchema, ConnectionRequestErrorCodes, ConnectionRequestFailedError, ConnectionRequestTimeoutError, ConnectionStatus, ConnectionStatuses, CreateAuthConfigParamsSchema, CreateAuthConfigResponseSchema, CreateComposioManagedAuthConfigParamsSchema, CreateConnectedAccountLinkOptionsSchema, CreateConnectedAccountLinkResponseSchema, CreateConnectedAccountOptionsSchema, CreateConnectedAccountParamsSchema, CreateConnectedAccountResponseSchema, CreateCustomAuthConfigParamsSchema, CustomAuthParamsSchema, CustomConnectionDataSchema, CustomCreateResponseSchema, CustomOauth1ConnectionDataSchema, CustomOauth2ConnectionDataSchema, DefaultCreateConnectedAccountParamsSchema, GenerateURLParamsSchema, GenerateURLResponseSchema, IncomingTriggerPayloadSchema, JSONSchemaPropertySchema, JsonSchemaToZodError, MCP, MCPAuthOptionsSchema, MCPGenerateURLParamsSchema, MCPGetServerParamsSchema, MCPMultiAppServerSchema, MCPServerCreateResponseSchema, MCPServerListResponseSchema, MCPServerSchema, MCPServerTypeSchema, MCPServerUpdateParamsSchema, MCPSingleAppServerSchema, MCPToolkitConfigSchema, MCPToolkitConfigsArraySchema, McpDeleteResponseSchema, McpListResponseSchema, McpRetrieveResponseSchema, McpUpdateResponseSchema, Oauth1ActiveConnectionDataSchema, Oauth1ConnectionDataSchema, Oauth1ExpiredConnectionDataSchema, Oauth1FailedConnectionDataSchema, Oauth1InactiveConnectionDataSchema, Oauth1InitiatedConnectionDataSchema, Oauth1InitiatingConnectionDataSchema, Oauth2ActiveConnectionDataSchema, Oauth2ConnectionDataSchema, Oauth2ExpiredConnectionDataSchema, Oauth2FailedConnectionDataSchema, Oauth2InactiveConnectionDataSchema, Oauth2InitiatedConnectionDataSchema, Oauth2InitiatingConnectionDataSchema, OpenAIProvider, RedirectableAuthSchemeSchema, SDKErrorCodes, ToolErrorCodes, ToolExecuteMetaParamsSchema, ToolExecuteParamsSchema, ToolExecuteResponseSchema, ToolKitItemSchema, ToolKitListResponseSchema, ToolKitMetaSchema, ToolListParamsSchema, ToolListResponseSchema, ToolProxyParamsSchema, ToolRouterConfigManageConnectionsSchema, ToolRouterConfigTagsSchema, ToolRouterConfigToolsSchema, ToolRouterCreateSessionConfigSchema, ToolRouterMCPServerConfigSchema, ToolRouterManageConnectionsConfigSchema, ToolRouterTagsEnableDisableSchema, ToolRouterTagsParamSchema, ToolRouterToolkitsDisabledConfigSchema, ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsOptionsSchema, ToolRouterToolkitsParamSchema, ToolRouterToolsParamSchema, ToolSchema, ToolkitAuthConfigDetailsSchema, ToolkitAuthFieldSchema, ToolkitAuthFieldsResponseSchema, ToolkitCategorySchema, ToolkitConnectionStateSchema, ToolkitConnectionsDetailsSchema, ToolkitErrorCodes, ToolkitLatestVersionSchema, ToolkitMangedByEnumSchema, ToolkitRetrieveCategoriesResponseSchema, ToolkitRetrieveResponseSchema, ToolkitSchema, ToolkitSortByEnumSchema, ToolkitVersionParamSchema, ToolkitVersionSchema, ToolkitVersionsSchema, ToolkitsListParamsSchema, TriggerErrorCodes, TriggerInstanceListActiveParamsSchema, TriggerInstanceListActiveResponseItemSchema, TriggerInstanceListActiveResponseSchema, TriggerInstanceManageDeleteResponseSchema, TriggerInstanceManageUpdateParamsSchema, TriggerInstanceManageUpdateResponseSchema, TriggerInstanceUpsertParamsSchema, TriggerInstanceUpsertResponseSchema, TriggerStatusEnum, TriggerStatuses, TriggerSubscribeParamSchema, TriggerTypeSchema, TriggersTypeListParamsSchema, TriggersTypeListResponseSchema, ValidationError, ValidationErrorCodes, VerifyWebhookParamsSchema, constants_exports as constants, createConnectionRequest, handleToolExecutionError, jsonSchemaToZodSchema, logger_default as logger, removeNonRequiredProperties };
|
|
6664
|
+
export { AuthConfigCreationToolAccessConfigSchema, AuthConfigErrorCodes, AuthConfigListParamsSchema, AuthConfigListResponseSchema, AuthConfigRetrieveResponseSchema, AuthConfigToolAccessConfigSchema, AuthConfigTypes, AuthConfigUpdateParamsSchema, AuthCustomConfigUpdateParamsSchema, AuthDefaultConfigUpdateParamsSchema, AuthScheme, AuthSchemeEnum, AuthSchemeTypes, BaseAgenticProvider, BaseNonAgenticProvider, BillcomAuthConnectionDataSchema, Composio, ComposioAuthConfigNotFoundError, ComposioConnectedAccountNotFoundError, ComposioCustomCreateResponseSchema, ComposioCustomToolsNotInitializedError, ComposioError, ComposioFailedToCreateConnectedAccountLink, ComposioFailedToCreatePusherClientError, ComposioFailedToGetSDKRealtimeCredentialsError, ComposioFailedToSubscribeToPusherChannelError, ComposioFailedToUnsubscribeFromPusherChannelError, ComposioGenerateURLParamsSchema, ComposioGenerateURLResponseSchema, ComposioGlobalExecuteToolFnNotSetError, ComposioInvalidExecuteFunctionError, ComposioInvalidModifierError, ComposioMcpDeleteResponseSchema, ComposioMcpListResponseSchema, ComposioMcpRetrieveResponseSchema, ComposioMcpUpdateResponseSchema, ComposioMultipleConnectedAccountsError, ComposioNoAPIKeyError, ComposioProvider, ComposioProviderNotDefinedError, ComposioToolExecutionError, ComposioToolNotFoundError, ComposioToolVersionRequiredError, ComposioToolkitFetchError, ComposioToolkitNotFoundError, ComposioTriggerTypeNotFoundError, ComposioWebhookPayloadError, ComposioWebhookSignatureVerificationError, ConnectedAccountAuthConfigSchema, ConnectedAccountErrorCodes, ConnectedAccountListParamsSchema, ConnectedAccountListResponseSchema, ConnectedAccountRetrieveResponseSchema, ConnectedAccountStatusSchema, ConnectedAccountStatuses, ConnectionDataSchema, ConnectionRequestErrorCodes, ConnectionRequestFailedError, ConnectionRequestTimeoutError, ConnectionStatus, ConnectionStatuses, CreateAuthConfigParamsSchema, CreateAuthConfigResponseSchema, CreateComposioManagedAuthConfigParamsSchema, CreateConnectedAccountLinkOptionsSchema, CreateConnectedAccountLinkResponseSchema, CreateConnectedAccountOptionsSchema, CreateConnectedAccountParamsSchema, CreateConnectedAccountResponseSchema, CreateCustomAuthConfigParamsSchema, CustomAuthParamsSchema, CustomConnectionDataSchema, CustomCreateResponseSchema, CustomOauth1ConnectionDataSchema, CustomOauth2ConnectionDataSchema, DefaultCreateConnectedAccountParamsSchema, GenerateURLParamsSchema, GenerateURLResponseSchema, IncomingTriggerPayloadSchema, JSONSchemaPropertySchema, JsonSchemaToZodError, MCP, MCPAuthOptionsSchema, MCPGenerateURLParamsSchema, MCPGetServerParamsSchema, MCPMultiAppServerSchema, MCPServerCreateResponseSchema, MCPServerListResponseSchema, MCPServerSchema, MCPServerTypeSchema, MCPServerUpdateParamsSchema, MCPSingleAppServerSchema, MCPToolkitConfigSchema, MCPToolkitConfigsArraySchema, McpDeleteResponseSchema, McpListResponseSchema, McpRetrieveResponseSchema, McpUpdateResponseSchema, Oauth1ActiveConnectionDataSchema, Oauth1ConnectionDataSchema, Oauth1ExpiredConnectionDataSchema, Oauth1FailedConnectionDataSchema, Oauth1InactiveConnectionDataSchema, Oauth1InitiatedConnectionDataSchema, Oauth1InitiatingConnectionDataSchema, Oauth2ActiveConnectionDataSchema, Oauth2ConnectionDataSchema, Oauth2ExpiredConnectionDataSchema, Oauth2FailedConnectionDataSchema, Oauth2InactiveConnectionDataSchema, Oauth2InitiatedConnectionDataSchema, Oauth2InitiatingConnectionDataSchema, OpenAIProvider, RedirectableAuthSchemeSchema, SDKErrorCodes, ToolErrorCodes, ToolExecuteMetaParamsSchema, ToolExecuteParamsSchema, ToolExecuteResponseSchema, ToolKitItemSchema, ToolKitListResponseSchema, ToolKitMetaSchema, ToolListParamsSchema, ToolListResponseSchema, ToolProxyParamsSchema, ToolRouterConfigManageConnectionsSchema, ToolRouterConfigTagsSchema, ToolRouterConfigToolsSchema, ToolRouterCreateSessionConfigSchema, ToolRouterMCPServerConfigSchema, ToolRouterManageConnectionsConfigSchema, ToolRouterTagsEnableDisableSchema, ToolRouterTagsParamSchema, ToolRouterToolkitsDisabledConfigSchema, ToolRouterToolkitsEnabledConfigSchema, ToolRouterToolkitsOptionsSchema, ToolRouterToolkitsParamSchema, ToolRouterToolsParamSchema, ToolSchema, ToolkitAuthConfigDetailsSchema, ToolkitAuthFieldSchema, ToolkitAuthFieldsResponseSchema, ToolkitCategorySchema, ToolkitConnectionStateSchema, ToolkitConnectionsDetailsSchema, ToolkitErrorCodes, ToolkitLatestVersionSchema, ToolkitMangedByEnumSchema, ToolkitRetrieveCategoriesResponseSchema, ToolkitRetrieveResponseSchema, ToolkitSchema, ToolkitSortByEnumSchema, ToolkitVersionParamSchema, ToolkitVersionSchema, ToolkitVersionsSchema, ToolkitsListParamsSchema, TriggerErrorCodes, TriggerInstanceListActiveParamsSchema, TriggerInstanceListActiveResponseItemSchema, TriggerInstanceListActiveResponseSchema, TriggerInstanceManageDeleteResponseSchema, TriggerInstanceManageUpdateParamsSchema, TriggerInstanceManageUpdateResponseSchema, TriggerInstanceUpsertParamsSchema, TriggerInstanceUpsertResponseSchema, TriggerStatusEnum, TriggerStatuses, TriggerSubscribeParamSchema, TriggerTypeSchema, TriggersTypeListParamsSchema, TriggersTypeListResponseSchema, ValidationError, ValidationErrorCodes, VerifyWebhookParamsSchema, WebhookPayloadSchema, WebhookPayloadV1Schema, WebhookPayloadV2Schema, WebhookPayloadV3Schema, WebhookVersions, constants_exports as constants, createConnectionRequest, handleToolExecutionError, jsonSchemaToZodSchema, logger_default as logger, removeNonRequiredProperties };
|