diff --git a/.github/workflows/lint_js.yml b/.github/workflows/lint_js.yml new file mode 100644 index 0000000000..1c30a041f7 --- /dev/null +++ b/.github/workflows/lint_js.yml @@ -0,0 +1,42 @@ +name: Check Linting and Formatting (JS) + +on: + push: + paths: + - '**/*.js' + - '**/*.ts' + pull_request: + paths: + - '**/*.js' + - '**/*.ts' + +jobs: + lint-and-prettify: + runs-on: ubuntu-latest + + defaults: + run: + working-directory: js + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install pnpm + run: npm install -g pnpm + + - name: Install packages in js folder + run: pnpm install --frozen-lockfile + + - name: Run ESLint + run: pnpm run eslint + continue-on-error: false + + - name: Run Prettier + run: pnpm run prettier:check + continue-on-error: false \ No newline at end of file diff --git a/js/.prettierrc b/js/.prettierrc new file mode 100644 index 0000000000..b530aa955a --- /dev/null +++ b/js/.prettierrc @@ -0,0 +1,24 @@ + +{ + "arrowParens": "always", + "bracketSpacing": true, + "endOfLine": "lf", + "htmlWhitespaceSensitivity": "css", + "insertPragma": false, + "singleAttributePerLine": false, + "bracketSameLine": false, + "jsxBracketSameLine": false, + "jsxSingleQuote": false, + "printWidth": 80, + "proseWrap": "preserve", + "quoteProps": "as-needed", + "requirePragma": false, + "semi": true, + "singleQuote": false, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false, + "embeddedLanguageFormatting": "auto", + "vueIndentScriptAndStyle": false, + "experimentalTernaries": false + } \ No newline at end of file diff --git a/js/eslint.config.mjs b/js/eslint.config.mjs index 2b8fb9a1dc..5c64cb22ae 100644 --- a/js/eslint.config.mjs +++ b/js/eslint.config.mjs @@ -1,30 +1,34 @@ import globals from "globals"; -import pluginJs from "@eslint/js"; import tseslint from "typescript-eslint"; -import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'; + +/** @type {import('eslint').Linter.Config[]} */ export default [ - {languageOptions: { globals: globals.node },}, - pluginJs.configs.recommended, - // eslintPluginPrettierRecommended, + {files: ["src/**/*.{ts,js}"]}, + {languageOptions: { globals: globals.browser }}, ...tseslint.configs.recommended, { rules: { "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-require-imports": "warn", + "@typescript-eslint/no-unsafe-function-type": "off", "no-prototype-builtins": "off", - "@typescript-eslint/ban-types": "error", "max-lines-per-function": ["error", 250], "no-unused-vars": "off", "@typescript-eslint/ban-ts-comment": "off", "no-constant-condition": "off", "no-ex-assign": "off", "no-constant-binary-expression": "off", + "@typescript-eslint/no-empty-object-type": "warn", "@typescript-eslint/no-non-null-asserted-optional-chain": "off", "no-unsafe-optional-chaining": "off", "no-extra-boolean-cast": "off", - "no-console": "error", + "no-var": "warn", + "prefer-const": "warn", + "no-console": "warn", + "@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/no-unused-vars": [ - "warn", // or "error" + "warn", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_", @@ -34,4 +38,3 @@ export default [ }, }, ]; - diff --git a/js/package.json b/js/package.json index 9196d9d155..1e7cac7550 100644 --- a/js/package.json +++ b/js/package.json @@ -2,7 +2,7 @@ "name": "composio-core", "version": "0.3.2", "description": "", - "main": "dist/src/index.js", + "main": "dist/index.js", "scripts": { "test": "jest --testMatch=\"**/*.spec.ts\"", "test:watch": "jest --testMatch=\"**/*.spec.ts\" --watch", @@ -11,14 +11,16 @@ "openapispec:generate": "npx @hey-api/openapi-ts", "run:cli": "ts-node src/cli/index.ts", "run:sample": "ts-node sample.ts", - "build": "rollup -c rollup.config.mjs", + "eslint": "eslint 'src/**/*.{ts,js}' --max-warnings=281", + "prettier": "prettier --write 'src/**/*.{ts,js,cjs}'", + "prettier:check": "prettier --check 'src/**/*.{ts,js,mjs,cjs}'", + "build": "rollup -c rollup.config.mjs && ./setup_cli.sh", "lint": "eslint 'src/**/*.ts'", - "prettier": "prettier --write 'src/**/*.ts'", "format": "pnpm lint && pnpm prettier" }, "bin": { - "composio-js": "./dist/src/cli/index", - "composio": "./dist/src/cli/index" + "composio-js": "./dist/cli/index", + "composio": "./dist/cli/index" }, "lint-staged": { "src/**/*.{js,jsx,ts,tsx}": "eslint --fix" @@ -27,11 +29,22 @@ "author": "Utkarsh Dixit ", "license": "ISC", "devDependencies": { + "@ai-sdk/openai": "^0.0.36", "@cloudflare/workers-types": "^4.20240718.0", + "@e2b/code-interpreter": "^0.0.8", + "@e2b/sdk": "^0.16.1", + "@eslint/js": "^9.16.0", + "@faker-js/faker": "^8.4.1", + "@hey-api/client-axios": "^0.2.3", "@hey-api/openapi-ts": "^0.52.4", + "@hono/node-server": "^1.12.0", "@jest/globals": "^29.7.0", - "@rollup/plugin-commonjs": "^25.0.7", + "@langchain/core": "^0.2.18", + "@langchain/openai": "^0.2.5", + "@rollup/plugin-commonjs": "^25.0.8", + "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^15.2.3", + "@rollup/plugin-replace": "^6.0.1", "@rollup/plugin-typescript": "^11.1.6", "@swc/core": "^1.7.10", "@swc/helpers": "^0.5.12", @@ -42,30 +55,9 @@ "@types/node": "^20.14.2", "@types/uuid": "^10.0.0", "@types/winston": "^2.4.4", - "axios-mock-adapter": "^2.1.0", - "jest": "^29.7.0", - "jest-html-reporters": "^3.1.7", - "regenerator-runtime": "^0.14.1", - "rollup": "^4.9.1", - "rollup-plugin-dts": "^6.1.0", - "ts-jest": "^29.1.2", - "ts-loader": "^9.5.1", - "tslib": "^2.6.2", - "typedoc": "^0.25.13", - "typescript": "^5.4.5", - "wrangler": "^3.63.1", - "@ai-sdk/openai": "^0.0.36", - "@e2b/code-interpreter": "^0.0.8", - "@e2b/sdk": "^0.16.1", - "@faker-js/faker": "^8.4.1", - "@hey-api/client-axios": "^0.2.3", - "@hono/node-server": "^1.12.0", - "@langchain/core": "^0.2.18", - "@langchain/openai": "^0.2.5", - "@rollup/plugin-json": "^6.1.0", - "@rollup/plugin-replace": "^6.0.1", "ai": "^3.2.22", "axios": "^1.7.2", + "axios-mock-adapter": "^2.1.0", "chalk": "^4", "cli-progress": "^3.12.0", "colors": "^1.4.0", @@ -73,22 +65,35 @@ "dockerode": "^4.0.2", "e2b": "^0.16.1", "enumify": "^2.0.0", + "eslint": "^9.16.0", + "globals": "^15.13.0", "hono": "^4.4.11", "inquirer": "^10.2.2", + "jest": "^29.7.0", + "jest-html-reporters": "^3.1.7", "langchain": "^0.2.11", "open": "^8.4.0", "openai": "^4.50.0", + "prettier": "^3.4.2", "pusher-js": "8.4.0-rc2", + "regenerator-runtime": "^0.14.1", "resolve-package-path": "^4.0.3", + "rollup": "^4.9.1", + "rollup-plugin-dts": "^6.1.0", "rollup-plugin-terser": "^7.0.2", + "ts-jest": "^29.1.2", + "ts-loader": "^9.5.1", "ts-node": "^10.9.2", + "tslib": "^2.6.2", + "typedoc": "^0.25.13", + "typescript": "^5.4.5", + "typescript-eslint": "^8.17.0", "uuid": "^10.0.0", "winston": "^3.13.1", + "wrangler": "^3.63.1", "zod": "^3.23.8", "zod-to-json-schema": "^3.23.2" }, - "dependencies": { - }, "publishConfig": { "access": "public" } diff --git a/js/pnpm-lock.yaml b/js/pnpm-lock.yaml index 1c30f3beb0..1d89b462c4 100644 --- a/js/pnpm-lock.yaml +++ b/js/pnpm-lock.yaml @@ -20,6 +20,9 @@ importers: '@e2b/sdk': specifier: ^0.16.1 version: 0.16.1 + '@eslint/js': + specifier: ^9.16.0 + version: 9.16.0 '@faker-js/faker': specifier: ^8.4.1 version: 8.4.1 @@ -37,12 +40,12 @@ importers: version: 29.7.0 '@langchain/core': specifier: ^0.2.18 - version: 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + version: 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) '@langchain/openai': specifier: ^0.2.5 - version: 0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))) + version: 0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))) '@rollup/plugin-commonjs': - specifier: ^25.0.7 + specifier: ^25.0.8 version: 25.0.8(rollup@4.28.1) '@rollup/plugin-json': specifier: ^6.1.0 @@ -113,6 +116,12 @@ importers: enumify: specifier: ^2.0.0 version: 2.0.0 + eslint: + specifier: ^9.16.0 + version: 9.16.0(jiti@1.21.6) + globals: + specifier: ^15.13.0 + version: 15.13.0 hono: specifier: ^4.4.11 version: 4.4.12 @@ -127,13 +136,16 @@ importers: version: 3.1.7 langchain: specifier: ^0.2.11 - version: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) + version: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) open: specifier: ^8.4.0 version: 8.4.2 openai: specifier: ^4.50.0 version: 4.51.0 + prettier: + specifier: ^3.4.2 + version: 3.4.2 pusher-js: specifier: 8.4.0-rc2 version: 8.4.0-rc2 @@ -170,6 +182,9 @@ importers: typescript: specifier: ^5.4.5 version: 5.4.5 + typescript-eslint: + specifier: ^8.17.0 + version: 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) uuid: specifier: ^10.0.0 version: 10.0.0 @@ -647,6 +662,40 @@ packages: cpu: [x64] os: [win32] + '@eslint-community/eslint-utils@4.4.1': + resolution: {integrity: sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.1': + resolution: {integrity: sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.19.1': + resolution: {integrity: sha512-fo6Mtm5mWyKjA/Chy1BYTdn5mGJoDNjC7C64ug20ADsRDGrA85bN3uK3MaKbeRkRuuIEAR5N33Jr1pbm411/PA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/core@0.9.1': + resolution: {integrity: sha512-GuUdqkyyzQI5RMIWkHhvTWLCyLo1jNK3vzkSyaExH5kHPDHcuL2VOpHjmMY+y3+NC69qAKToBqldTBgYeLSr9Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/eslintrc@3.2.0': + resolution: {integrity: sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/js@9.16.0': + resolution: {integrity: sha512-tw2HxzQkrbeuvyj1tG2Yqq+0H9wGoI2IMk4EOsQeX+vmd75FtJAzf+gTA69WF+baUKRYQ3x2kbLE08js5OsTVg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/object-schema@2.1.5': + resolution: {integrity: sha512-o0bhxnL89h5Bae5T318nFoFzGy+YE5i/gGkoPAgkmTVdRKTiv3p8JHevPiPaMwoloKfEiiaHlawCqaZMqRm+XQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/plugin-kit@0.2.4': + resolution: {integrity: sha512-zSkKow6H5Kdm0ZUQUB2kV5JIXqoG0+uH5YADhaEHswm664N9Db8dXSi0nMJpacpMf+MyyglF1vnZohpEg5yUtg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@faker-js/faker@8.4.1': resolution: {integrity: sha512-XQ3cU+Q8Uqmrbf2e0cIC/QN43sTBSC8KF12u29Mb47tWrt2hAgBXSgpZMj4Ao8Uk0iJcU99QsOCaIL8934obCg==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0, npm: '>=6.14.13'} @@ -671,6 +720,26 @@ packages: resolution: {integrity: sha512-e6oHjNiErRxsZRZBmc2KucuvY3btlO/XPncIpP2X75bRdTilF9GLjm3NHvKKunpJbbJJj31/FoPTksTf8djAVw==} engines: {node: '>=18.14.1'} + '@humanfs/core@0.19.1': + resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.6': + resolution: {integrity: sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.3.1': + resolution: {integrity: sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA==} + engines: {node: '>=18.18'} + + '@humanwhocodes/retry@0.4.1': + resolution: {integrity: sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA==} + engines: {node: '>=18.18'} + '@inquirer/checkbox@2.5.0': resolution: {integrity: sha512-sMgdETOfi2dUHT8r7TT1BTKOwNvdDGFDXYWtQ2J69SvlYNntk9I/gJe7r5yvMwwsuKnYbuRs3pNhx4tgNck5aA==} engines: {node: '>=18'} @@ -843,6 +912,18 @@ packages: resolution: {integrity: sha512-cXWgKE3sdWLSqAa8ykbCcUsUF1Kyr5J3HOWYGuobhPEycXW4WI++d5DhzdpL238mzoEXTi90VqfSCra37l5YqA==} engines: {node: '>=18'} + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + '@opentelemetry/api@1.9.0': resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==} engines: {node: '>=8.0.0'} @@ -1209,6 +1290,68 @@ packages: '@types/yargs@17.0.33': resolution: {integrity: sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==} + '@typescript-eslint/eslint-plugin@8.17.0': + resolution: {integrity: sha512-HU1KAdW3Tt8zQkdvNoIijfWDMvdSweFYm4hWh+KwhPstv+sCmWb89hCIP8msFm9N1R/ooh9honpSuvqKWlYy3w==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.0.0 || ^8.0.0-alpha.0 + eslint: ^8.57.0 || ^9.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/parser@8.17.0': + resolution: {integrity: sha512-Drp39TXuUlD49F7ilHHCG7TTg8IkA+hxCuULdmzWYICxGXvDXmDmWEjJYZQYgf6l/TFfYNE167m7isnc3xlIEg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/scope-manager@8.17.0': + resolution: {integrity: sha512-/ewp4XjvnxaREtqsZjF4Mfn078RD/9GmiEAtTeLQ7yFdKnqwTOgRMSvFz4et9U5RiJQ15WTGXPLj89zGusvxBg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/type-utils@8.17.0': + resolution: {integrity: sha512-q38llWJYPd63rRnJ6wY/ZQqIzPrBCkPdpIsaCfkR3Q4t3p6sb422zougfad4TFW9+ElIFLVDzWGiGAfbb/v2qw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/types@8.17.0': + resolution: {integrity: sha512-gY2TVzeve3z6crqh2Ic7Cr+CAv6pfb0Egee7J5UAVWCpVvDI/F71wNfolIim4FE6hT15EbpZFVUj9j5i38jYXA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.17.0': + resolution: {integrity: sha512-JqkOopc1nRKZpX+opvKqnM3XUlM7LpFMD0lYxTqOTKQfCWAmxw45e3qlOCsEqEB2yuacujivudOFpCnqkBDNMw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/utils@8.17.0': + resolution: {integrity: sha512-bQC8BnEkxqG8HBGKwG9wXlZqg37RKSMY7v/X8VEWD8JG2JuTHuNK0VFvMPMUKQcbk6B+tf05k+4AShAEtCtJ/w==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@typescript-eslint/visitor-keys@8.17.0': + resolution: {integrity: sha512-1Hm7THLpO6ww5QU6H/Qp+AusUUl+z/CAm3cNZZ0jQvon9yicgO7Rwd+/WWRpMKLYV6p2UvdbR27c86rzCPpreg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@vue/compiler-core@3.4.36': resolution: {integrity: sha512-qBkndgpwFKdupmOPoiS10i7oFdN7a+4UNDlezD0GlQ1kuA1pNrscg9g12HnB5E8hrWSuEftRsbJhL1HI2zpJhg==} @@ -1298,6 +1441,11 @@ packages: peerDependencies: acorn: ^8 + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + acorn-walk@8.3.3: resolution: {integrity: sha512-MxXdReSRhGO7VlFe1bRG/oI7/mdLV9B9JJT0N8vZOhF7gFRR5l3M8W9G8JxmKV+JC5mGqJ0QvqfSOLsCPa4nUw==} engines: {node: '>=0.4.0'} @@ -1307,6 +1455,11 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + acorn@8.14.0: + resolution: {integrity: sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==} + engines: {node: '>=0.4.0'} + hasBin: true + agentkeepalive@4.5.0: resolution: {integrity: sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==} engines: {node: '>= 8.0.0'} @@ -1659,6 +1812,10 @@ packages: resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} engines: {node: '>= 8'} + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + css-tree@2.3.1: resolution: {integrity: sha512-6Fv1DV/TYw//QF5IzQdqsNDjx/wc8TrMBZsqjL9eW01tWb7R7k/mq+/VXfJCl7SoD5emsJop9cOByJZfs8hYIw==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} @@ -1693,6 +1850,9 @@ packages: babel-plugin-macros: optional: true + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + deepmerge@4.3.1: resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} engines: {node: '>=0.10.0'} @@ -1809,11 +1969,41 @@ packages: resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} engines: {node: '>=8.0.0'} + eslint-scope@8.2.0: + resolution: {integrity: sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@4.2.0: + resolution: {integrity: sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint@9.16.0: + resolution: {integrity: sha512-whp8mSQI4C8VXd+fLgSM0lh3UlmcFtVwUQjyKCFfsp+2ItAIYhlq/hqGahGqHE6cv9unM41VlqKk2VtKYR2TaA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@10.3.0: + resolution: {integrity: sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + esprima@4.0.1: resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} engines: {node: '>=4'} hasBin: true + esquery@1.6.0: + resolution: {integrity: sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==} + engines: {node: '>=0.10'} + esrecurse@4.3.0: resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} engines: {node: '>=4.0'} @@ -1835,6 +2025,10 @@ packages: estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + event-target-shim@5.0.1: resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} engines: {node: '>=6'} @@ -1877,15 +2071,29 @@ packages: fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + fast-glob@3.3.2: + resolution: {integrity: sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==} + engines: {node: '>=8.6.0'} + fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fastq@1.17.1: + resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==} + fb-watchman@2.0.2: resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} fecha@4.2.3: resolution: {integrity: sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==} + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + filelist@1.0.4: resolution: {integrity: sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==} @@ -1897,6 +2105,17 @@ packages: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.3.2: + resolution: {integrity: sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==} + fn.name@1.1.0: resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==} @@ -1973,6 +2192,10 @@ packages: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + glob-to-regexp@0.4.1: resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} @@ -1989,9 +2212,20 @@ packages: resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==} engines: {node: '>=4'} + globals@14.0.0: + resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} + engines: {node: '>=18'} + + globals@15.13.0: + resolution: {integrity: sha512-49TewVEz0UxZjr1WYYsWpPrhyC/B/pA8Bq0fUmet2n+eR7yn0IvNzNaoBwnK6mdkzcN+se7Ez9zUgULTz2QH4g==} + engines: {node: '>=18'} + graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + graphemer@1.4.0: + resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} + handlebars@4.7.8: resolution: {integrity: sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==} engines: {node: '>=0.4.7'} @@ -2034,6 +2268,14 @@ packages: ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + import-fresh@3.3.0: + resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==} + engines: {node: '>=6'} + import-local@3.1.0: resolution: {integrity: sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==} engines: {node: '>=8'} @@ -2317,6 +2559,9 @@ packages: engines: {node: '>=4'} hasBin: true + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + json-parse-even-better-errors@2.3.1: resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} @@ -2326,6 +2571,9 @@ packages: json-schema@0.4.0: resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} @@ -2346,6 +2594,9 @@ packages: resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} engines: {node: '>=0.10.0'} + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + kleur@3.0.3: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} engines: {node: '>=6'} @@ -2554,6 +2805,10 @@ packages: resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} engines: {node: '>=6'} + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} @@ -2568,9 +2823,16 @@ packages: resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} engines: {node: '>=8'} + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + lodash.memoize@4.1.2: resolution: {integrity: sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==} + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + logform@2.6.1: resolution: {integrity: sha512-CdaO738xRapbKIMVn2m4F6KTj4j7ooJ8POVnebSgKo3KBz5axNXRAL7ZdRjIV6NOr2Uf4vjtRkxrFETOioCqSA==} engines: {node: '>= 12.0.0'} @@ -2612,6 +2874,10 @@ packages: merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + micromatch@4.0.7: resolution: {integrity: sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==} engines: {node: '>=8.6'} @@ -2800,6 +3066,10 @@ packages: resolution: {integrity: sha512-smLZPck4OkKMNExcw8jMgrMOGgVGx2N/s6DbKL2ftNl77g5HfoGpZGFy79RBzU/EkaO0OZpwBnslfdBfh7ZcWg==} engines: {node: '>= 12.0.0', npm: '>= 7.0.0'} + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + os-tmpdir@1.0.2: resolution: {integrity: sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==} engines: {node: '>=0.10.0'} @@ -2820,6 +3090,10 @@ packages: resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} engines: {node: '>=8'} + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + p-queue@6.6.2: resolution: {integrity: sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==} engines: {node: '>=8'} @@ -2836,6 +3110,10 @@ packages: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + parse-json@5.2.0: resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} engines: {node: '>=8'} @@ -2911,6 +3189,15 @@ packages: resolution: {integrity: sha512-TesUflQ0WKZqAvg52PWL6kHgLKP6xB6heTOdoYM0Wt2UHyxNa4K25EZZMgKns3BH1RLVbZCREPpLY0rhnNoHVQ==} engines: {node: ^10 || ^12 || >=14} + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + prettier@3.4.2: + resolution: {integrity: sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==} + engines: {node: '>=14'} + hasBin: true + pretty-format@29.7.0: resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -2938,6 +3225,9 @@ packages: pusher-js@8.4.0-rc2: resolution: {integrity: sha512-d87GjOEEl9QgO5BWmViSqW0LOzPvybvX6WA9zLUstNdB57jVJuR27zHkRnrav2a3+zAMlHbP2Og8wug+rG8T+g==} + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + randombytes@2.1.0: resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} @@ -2970,6 +3260,10 @@ packages: resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==} engines: {node: '>=8'} + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + resolve-from@5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} @@ -2990,6 +3284,10 @@ packages: resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==} engines: {node: '>= 4'} + reusify@1.0.4: + resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + rollup-plugin-dts@6.1.1: resolution: {integrity: sha512-aSHRcJ6KG2IHIioYlvAOcEq6U99sVtqDDKVhnwt70rW6tsz3tv5OSjEiWcgzfsHdLyGXZ/3b/7b/+Za3Y6r1XA==} engines: {node: '>=16'} @@ -3022,6 +3320,9 @@ packages: resolution: {integrity: sha512-540WwVDOMxA6dN6We19EcT9sc3hkXPw5mzRNGM3FkdN/vtE9NFvj5lFAPNwUDmJjXidm3v7TC1cTE7t17Ulm1Q==} engines: {node: '>=0.12.0'} + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + rxjs@7.8.1: resolution: {integrity: sha512-AA3TVj+0A2iuIoQkWEK/tqFjBq2j+6PO6Y0zJcvzLAFhEFIO3HL0vls9hWLncZbAAbK0mar7oZ4V079I/qPMxg==} @@ -3274,6 +3575,12 @@ packages: resolution: {integrity: sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==} engines: {node: '>= 14.0.0'} + ts-api-utils@1.4.3: + resolution: {integrity: sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==} + engines: {node: '>=16'} + peerDependencies: + typescript: '>=4.2.0' + ts-jest@29.2.4: resolution: {integrity: sha512-3d6tgDyhCI29HlpwIq87sNuI+3Q6GLTTCeYRHCs7vDz+/3GCMwEtV9jezLyl4ZtnBgx00I7hm8PCP8cTksMGrw==} engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0} @@ -3328,6 +3635,10 @@ packages: tweetnacl@1.0.3: resolution: {integrity: sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==} + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + type-detect@4.0.8: resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} engines: {node: '>=4'} @@ -3343,6 +3654,16 @@ packages: peerDependencies: typescript: 4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x + typescript-eslint@8.17.0: + resolution: {integrity: sha512-409VXvFd/f1br1DCbuKNFqQpXICoTB+V51afcwG1pn1a3Cp92MqAUges3YjwEdQ0cMUoCIodjVDAYzyD8h3SYA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + typescript@5.4.5: resolution: {integrity: sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==} engines: {node: '>=14.17'} @@ -3471,6 +3792,10 @@ packages: resolution: {integrity: sha512-XEJvmKJglhTW2TgfpKdkpj0119Yn5AClR7LJ0rBNUQFx20mNQj3s1ukTA1i77q+YBaHYbcKtXpxgPqfdUPCIYA==} engines: {node: '>= 12.0.0'} + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + wordwrap@1.0.0: resolution: {integrity: sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==} @@ -3992,6 +4317,47 @@ snapshots: '@esbuild/win32-x64@0.17.19': optional: true + '@eslint-community/eslint-utils@4.4.1(eslint@9.16.0(jiti@1.21.6))': + dependencies: + eslint: 9.16.0(jiti@1.21.6) + eslint-visitor-keys: 3.4.3 + + '@eslint-community/regexpp@4.12.1': {} + + '@eslint/config-array@0.19.1': + dependencies: + '@eslint/object-schema': 2.1.5 + debug: 4.3.5 + minimatch: 3.1.2 + transitivePeerDependencies: + - supports-color + + '@eslint/core@0.9.1': + dependencies: + '@types/json-schema': 7.0.15 + + '@eslint/eslintrc@3.2.0': + dependencies: + ajv: 6.12.6 + debug: 4.3.5 + espree: 10.3.0 + globals: 14.0.0 + ignore: 5.3.2 + import-fresh: 3.3.0 + js-yaml: 4.1.0 + minimatch: 3.1.2 + strip-json-comments: 3.1.1 + transitivePeerDependencies: + - supports-color + + '@eslint/js@9.16.0': {} + + '@eslint/object-schema@2.1.5': {} + + '@eslint/plugin-kit@0.2.4': + dependencies: + levn: 0.4.1 + '@faker-js/faker@8.4.1': {} '@fastify/busboy@2.1.1': {} @@ -4012,6 +4378,19 @@ snapshots: '@hono/node-server@1.12.0': {} + '@humanfs/core@0.19.1': {} + + '@humanfs/node@0.16.6': + dependencies: + '@humanfs/core': 0.19.1 + '@humanwhocodes/retry': 0.3.1 + + '@humanwhocodes/module-importer@1.0.1': {} + + '@humanwhocodes/retry@0.3.1': {} + + '@humanwhocodes/retry@0.4.1': {} + '@inquirer/checkbox@2.5.0': dependencies: '@inquirer/core': 9.1.0 @@ -4312,13 +4691,13 @@ snapshots: '@jsdevtools/ono@7.1.3': {} - '@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0)': + '@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0)': dependencies: ansi-styles: 5.2.0 camelcase: 6.3.0 decamelize: 1.2.0 js-tiktoken: 1.0.12 - langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) mustache: 4.2.0 p-queue: 6.6.2 p-retry: 4.6.2 @@ -4329,13 +4708,13 @@ snapshots: - langchain - openai - '@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8))': + '@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8))': dependencies: ansi-styles: 5.2.0 camelcase: 6.3.0 decamelize: 1.2.0 js-tiktoken: 1.0.12 - langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)) + langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)) mustache: 4.2.0 p-queue: 6.6.2 p-retry: 4.6.2 @@ -4346,9 +4725,9 @@ snapshots: - langchain - openai - '@langchain/openai@0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))': + '@langchain/openai@0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))': dependencies: - '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)) + '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)) js-tiktoken: 1.0.12 openai: 4.55.1(zod@3.23.8) zod: 3.23.8 @@ -4357,14 +4736,26 @@ snapshots: - encoding - langchain - '@langchain/textsplitters@0.0.3(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0)': + '@langchain/textsplitters@0.0.3(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0)': dependencies: - '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) js-tiktoken: 1.0.12 transitivePeerDependencies: - langchain - openai + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.17.1 + '@opentelemetry/api@1.9.0': {} '@rollup/plugin-commonjs@25.0.8(rollup@4.28.1)': @@ -4680,6 +5071,88 @@ snapshots: dependencies: '@types/yargs-parser': 21.0.3 + '@typescript-eslint/eslint-plugin@8.17.0(@typescript-eslint/parser@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5))(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5)': + dependencies: + '@eslint-community/regexpp': 4.12.1 + '@typescript-eslint/parser': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + '@typescript-eslint/scope-manager': 8.17.0 + '@typescript-eslint/type-utils': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + '@typescript-eslint/utils': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + '@typescript-eslint/visitor-keys': 8.17.0 + eslint: 9.16.0(jiti@1.21.6) + graphemer: 1.4.0 + ignore: 5.3.2 + natural-compare: 1.4.0 + ts-api-utils: 1.4.3(typescript@5.4.5) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/parser@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5)': + dependencies: + '@typescript-eslint/scope-manager': 8.17.0 + '@typescript-eslint/types': 8.17.0 + '@typescript-eslint/typescript-estree': 8.17.0(typescript@5.4.5) + '@typescript-eslint/visitor-keys': 8.17.0 + debug: 4.3.5 + eslint: 9.16.0(jiti@1.21.6) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/scope-manager@8.17.0': + dependencies: + '@typescript-eslint/types': 8.17.0 + '@typescript-eslint/visitor-keys': 8.17.0 + + '@typescript-eslint/type-utils@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5)': + dependencies: + '@typescript-eslint/typescript-estree': 8.17.0(typescript@5.4.5) + '@typescript-eslint/utils': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + debug: 4.3.5 + eslint: 9.16.0(jiti@1.21.6) + ts-api-utils: 1.4.3(typescript@5.4.5) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/types@8.17.0': {} + + '@typescript-eslint/typescript-estree@8.17.0(typescript@5.4.5)': + dependencies: + '@typescript-eslint/types': 8.17.0 + '@typescript-eslint/visitor-keys': 8.17.0 + debug: 4.3.5 + fast-glob: 3.3.2 + is-glob: 4.0.3 + minimatch: 9.0.4 + semver: 7.6.3 + ts-api-utils: 1.4.3(typescript@5.4.5) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/utils@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5)': + dependencies: + '@eslint-community/eslint-utils': 4.4.1(eslint@9.16.0(jiti@1.21.6)) + '@typescript-eslint/scope-manager': 8.17.0 + '@typescript-eslint/types': 8.17.0 + '@typescript-eslint/typescript-estree': 8.17.0(typescript@5.4.5) + eslint: 9.16.0(jiti@1.21.6) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + + '@typescript-eslint/visitor-keys@8.17.0': + dependencies: + '@typescript-eslint/types': 8.17.0 + eslint-visitor-keys: 4.2.0 + '@vue/compiler-core@3.4.36': dependencies: '@babel/parser': 7.25.3 @@ -4818,9 +5291,13 @@ snapshots: dependencies: event-target-shim: 5.0.1 - acorn-import-attributes@1.9.5(acorn@8.11.3): + acorn-import-attributes@1.9.5(acorn@8.14.0): dependencies: - acorn: 8.11.3 + acorn: 8.14.0 + + acorn-jsx@5.3.2(acorn@8.14.0): + dependencies: + acorn: 8.14.0 acorn-walk@8.3.3: dependencies: @@ -4828,6 +5305,8 @@ snapshots: acorn@8.11.3: {} + acorn@8.14.0: {} + agentkeepalive@4.5.0: dependencies: humanize-ms: 1.2.1 @@ -5143,7 +5622,7 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.0 '@types/estree': 1.0.6 - acorn: 8.11.3 + acorn: 8.14.0 estree-walker: 3.0.3 periscopic: 3.1.0 @@ -5229,6 +5708,12 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + css-tree@2.3.1: dependencies: mdn-data: 2.0.30 @@ -5248,6 +5733,8 @@ snapshots: dedent@1.5.3: {} + deep-is@0.1.4: {} + deepmerge@4.3.1: {} define-lazy-prop@2.0.0: {} @@ -5368,8 +5855,68 @@ snapshots: esrecurse: 4.3.0 estraverse: 4.3.0 + eslint-scope@8.2.0: + dependencies: + esrecurse: 4.3.0 + estraverse: 5.3.0 + + eslint-visitor-keys@3.4.3: {} + + eslint-visitor-keys@4.2.0: {} + + eslint@9.16.0(jiti@1.21.6): + dependencies: + '@eslint-community/eslint-utils': 4.4.1(eslint@9.16.0(jiti@1.21.6)) + '@eslint-community/regexpp': 4.12.1 + '@eslint/config-array': 0.19.1 + '@eslint/core': 0.9.1 + '@eslint/eslintrc': 3.2.0 + '@eslint/js': 9.16.0 + '@eslint/plugin-kit': 0.2.4 + '@humanfs/node': 0.16.6 + '@humanwhocodes/module-importer': 1.0.1 + '@humanwhocodes/retry': 0.4.1 + '@types/estree': 1.0.6 + '@types/json-schema': 7.0.15 + ajv: 6.12.6 + chalk: 4.1.2 + cross-spawn: 7.0.6 + debug: 4.3.5 + escape-string-regexp: 4.0.0 + eslint-scope: 8.2.0 + eslint-visitor-keys: 4.2.0 + espree: 10.3.0 + esquery: 1.6.0 + esutils: 2.0.3 + fast-deep-equal: 3.1.3 + file-entry-cache: 8.0.0 + find-up: 5.0.0 + glob-parent: 6.0.2 + ignore: 5.3.2 + imurmurhash: 0.1.4 + is-glob: 4.0.3 + json-stable-stringify-without-jsonify: 1.0.1 + lodash.merge: 4.6.2 + minimatch: 3.1.2 + natural-compare: 1.4.0 + optionator: 0.9.4 + optionalDependencies: + jiti: 1.21.6 + transitivePeerDependencies: + - supports-color + + espree@10.3.0: + dependencies: + acorn: 8.14.0 + acorn-jsx: 5.3.2(acorn@8.14.0) + eslint-visitor-keys: 4.2.0 + esprima@4.0.1: {} + esquery@1.6.0: + dependencies: + estraverse: 5.3.0 + esrecurse@4.3.0: dependencies: estraverse: 5.3.0 @@ -5386,6 +5933,8 @@ snapshots: dependencies: '@types/estree': 1.0.6 + esutils@2.0.3: {} + event-target-shim@5.0.1: {} eventemitter3@4.0.7: {} @@ -5438,14 +5987,32 @@ snapshots: fast-deep-equal@3.1.3: {} + fast-glob@3.3.2: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.7 + fast-json-stable-stringify@2.1.0: {} + fast-levenshtein@2.0.6: {} + + fastq@1.17.1: + dependencies: + reusify: 1.0.4 + fb-watchman@2.0.2: dependencies: bser: 2.1.1 fecha@4.2.3: {} + file-entry-cache@8.0.0: + dependencies: + flat-cache: 4.0.1 + filelist@1.0.4: dependencies: minimatch: 5.1.6 @@ -5459,6 +6026,18 @@ snapshots: locate-path: 5.0.0 path-exists: 4.0.0 + find-up@5.0.0: + dependencies: + locate-path: 6.0.0 + path-exists: 4.0.0 + + flat-cache@4.0.1: + dependencies: + flatted: 3.3.2 + keyv: 4.5.4 + + flatted@3.3.2: {} + fn.name@1.1.0: {} follow-redirects@1.15.6: {} @@ -5525,6 +6104,10 @@ snapshots: dependencies: is-glob: 4.0.3 + glob-parent@6.0.2: + dependencies: + is-glob: 4.0.3 + glob-to-regexp@0.4.1: {} glob@7.2.3: @@ -5546,8 +6129,14 @@ snapshots: globals@11.12.0: {} + globals@14.0.0: {} + + globals@15.13.0: {} + graceful-fs@4.2.11: {} + graphemer@1.4.0: {} + handlebars@4.7.8: dependencies: minimist: 1.2.8 @@ -5583,6 +6172,13 @@ snapshots: ieee754@1.2.1: {} + ignore@5.3.2: {} + + import-fresh@3.3.0: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + import-local@3.1.0: dependencies: pkg-dir: 4.2.0 @@ -6053,12 +6649,16 @@ snapshots: jsesc@2.5.2: {} + json-buffer@3.0.1: {} + json-parse-even-better-errors@2.3.1: {} json-schema-traverse@0.4.1: {} json-schema@0.4.0: {} + json-stable-stringify-without-jsonify@1.0.1: {} + json5@2.2.3: {} jsonc-parser@3.2.1: {} @@ -6077,20 +6677,24 @@ snapshots: jsonpointer@5.0.1: {} + keyv@4.5.4: + dependencies: + json-buffer: 3.0.1 + kleur@3.0.3: {} kuler@2.0.0: {} - langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)): + langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)): dependencies: - '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) - '@langchain/openai': 0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))) - '@langchain/textsplitters': 0.0.3(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + '@langchain/openai': 0.2.6(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))) + '@langchain/textsplitters': 0.0.3(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) binary-extensions: 2.3.0 js-tiktoken: 1.0.12 js-yaml: 4.1.0 jsonpointer: 5.0.1 - langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + langsmith: 0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) openapi-types: 12.1.3 p-retry: 4.6.2 uuid: 10.0.0 @@ -6100,12 +6704,13 @@ snapshots: optionalDependencies: axios: 1.7.2 handlebars: 4.7.8 + ignore: 5.3.2 ws: 8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4) transitivePeerDependencies: - encoding - openai - langsmith@0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0): + langsmith@0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0): dependencies: '@types/uuid': 9.0.8 commander: 10.0.1 @@ -6114,11 +6719,11 @@ snapshots: semver: 7.6.3 uuid: 9.0.1 optionalDependencies: - '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) - langchain: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) + '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + langchain: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) openai: 4.51.0 - langsmith@0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)): + langsmith@0.1.41(@langchain/core@0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0))(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.55.1(zod@3.23.8)): dependencies: '@types/uuid': 9.0.8 commander: 10.0.1 @@ -6127,12 +6732,17 @@ snapshots: semver: 7.6.3 uuid: 9.0.1 optionalDependencies: - '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) - langchain: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) + '@langchain/core': 0.2.21(langchain@0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)))(openai@4.51.0) + langchain: 0.2.13(axios@1.7.2)(handlebars@4.7.8)(ignore@5.3.2)(openai@4.51.0)(ws@8.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.4)) openai: 4.55.1(zod@3.23.8) leven@3.1.0: {} + levn@0.4.1: + dependencies: + prelude-ls: 1.2.1 + type-check: 0.4.0 + lines-and-columns@1.2.4: {} loader-runner@4.3.0: {} @@ -6143,8 +6753,14 @@ snapshots: dependencies: p-locate: 4.1.0 + locate-path@6.0.0: + dependencies: + p-locate: 5.0.0 + lodash.memoize@4.1.2: {} + lodash.merge@4.6.2: {} + logform@2.6.1: dependencies: '@colors/colors': 1.6.0 @@ -6188,6 +6804,8 @@ snapshots: merge-stream@2.0.0: {} + merge2@1.4.1: {} + micromatch@4.0.7: dependencies: braces: 3.0.3 @@ -6369,6 +6987,15 @@ snapshots: openapi-typescript-fetch@1.1.3: {} + optionator@0.9.4: + dependencies: + deep-is: 0.1.4 + fast-levenshtein: 2.0.6 + levn: 0.4.1 + prelude-ls: 1.2.1 + type-check: 0.4.0 + word-wrap: 1.2.5 + os-tmpdir@1.0.2: {} p-finally@1.0.0: {} @@ -6385,6 +7012,10 @@ snapshots: dependencies: p-limit: 2.3.0 + p-locate@5.0.0: + dependencies: + p-limit: 3.1.0 + p-queue@6.6.2: dependencies: eventemitter3: 4.0.7 @@ -6401,6 +7032,10 @@ snapshots: p-try@2.2.0: {} + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + parse-json@5.2.0: dependencies: '@babel/code-frame': 7.24.7 @@ -6464,6 +7099,10 @@ snapshots: picocolors: 1.0.1 source-map-js: 1.2.0 + prelude-ls@1.2.1: {} + + prettier@3.4.2: {} + pretty-format@29.7.0: dependencies: '@jest/schemas': 29.6.3 @@ -6492,6 +7131,8 @@ snapshots: dependencies: tweetnacl: 1.0.3 + queue-microtask@1.2.3: {} + randombytes@2.1.0: dependencies: safe-buffer: 5.2.1 @@ -6525,6 +7166,8 @@ snapshots: dependencies: resolve-from: 5.0.0 + resolve-from@4.0.0: {} + resolve-from@5.0.0: {} resolve-package-path@4.0.3: @@ -6541,6 +7184,8 @@ snapshots: retry@0.13.1: {} + reusify@1.0.4: {} + rollup-plugin-dts@6.1.1(rollup@4.28.1)(typescript@5.4.5): dependencies: magic-string: 0.30.11 @@ -6598,6 +7243,10 @@ snapshots: run-async@3.0.0: {} + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + rxjs@7.8.1: dependencies: tslib: 2.6.3 @@ -6755,7 +7404,7 @@ snapshots: '@jridgewell/sourcemap-codec': 1.5.0 '@jridgewell/trace-mapping': 0.3.25 '@types/estree': 1.0.6 - acorn: 8.11.3 + acorn: 8.14.0 aria-query: 5.3.0 axobject-query: 4.1.0 code-red: 1.0.4 @@ -6847,6 +7496,10 @@ snapshots: triple-beam@1.4.1: {} + ts-api-utils@1.4.3(typescript@5.4.5): + dependencies: + typescript: 5.4.5 + ts-jest@29.2.4(@babel/core@7.25.2)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.25.2))(esbuild@0.17.19)(jest@29.7.0(@types/node@20.14.2)(ts-node@10.9.2(@swc/core@1.7.10(@swc/helpers@0.5.12))(@types/node@20.14.2)(typescript@5.4.5)))(typescript@5.4.5): dependencies: bs-logger: 0.2.6 @@ -6903,6 +7556,10 @@ snapshots: tweetnacl@1.0.3: {} + type-check@0.4.0: + dependencies: + prelude-ls: 1.2.1 + type-detect@4.0.8: {} type-fest@0.21.3: {} @@ -6915,6 +7572,17 @@ snapshots: shiki: 0.14.7 typescript: 5.4.5 + typescript-eslint@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5): + dependencies: + '@typescript-eslint/eslint-plugin': 8.17.0(@typescript-eslint/parser@8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5))(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + '@typescript-eslint/parser': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + '@typescript-eslint/utils': 8.17.0(eslint@9.16.0(jiti@1.21.6))(typescript@5.4.5) + eslint: 9.16.0(jiti@1.21.6) + optionalDependencies: + typescript: 5.4.5 + transitivePeerDependencies: + - supports-color + typescript@5.4.5: {} ufo@1.5.3: {} @@ -7012,8 +7680,8 @@ snapshots: '@webassemblyjs/ast': 1.12.1 '@webassemblyjs/wasm-edit': 1.12.1 '@webassemblyjs/wasm-parser': 1.12.1 - acorn: 8.11.3 - acorn-import-attributes: 1.9.5(acorn@8.11.3) + acorn: 8.14.0 + acorn-import-attributes: 1.9.5(acorn@8.14.0) browserslist: 4.23.1 chrome-trace-event: 1.0.4 enhanced-resolve: 5.17.0 @@ -7065,6 +7733,8 @@ snapshots: triple-beam: 1.4.1 winston-transport: 4.7.1 + word-wrap@1.2.5: {} + wordwrap@1.0.0: {} workerd@1.20240701.0: diff --git a/js/rollup.config.mjs b/js/rollup.config.mjs index d0146c698c..84e0a7c274 100644 --- a/js/rollup.config.mjs +++ b/js/rollup.config.mjs @@ -5,7 +5,6 @@ import dts from 'rollup-plugin-dts'; import json from '@rollup/plugin-json'; // Import the @rollup/plugin-json to handle JSON files const generateBundleAndTypeBundles = (file) => { - return [{ input: `src/${file}.ts`, output: [ @@ -75,4 +74,3 @@ export default [ ...generateBundleAndTypeBundles('frameworks/vercel'), ...generateBundleAndTypeBundles('sdk/index'), ]; - diff --git a/js/setup_cli.sh b/js/setup_cli.sh index bd08317628..e8e1875be8 100755 --- a/js/setup_cli.sh +++ b/js/setup_cli.sh @@ -1,12 +1,12 @@ -cp src/constants.js lib/src/constants.js - +# cp src/constants.js dist/cli/constants.js +cp src/constants.js dist/constants.js # mv lib/src/cli/index.js lib/src/cli/index cat < temp_file #!/usr/bin/env node -$(cat lib/src/cli/index.js) +$(cat dist/cli/index.js) EOF -mv temp_file lib/src/cli/index +mv temp_file dist/cli/index -rm lib/src/cli/index.js +rm dist/cli/index.js diff --git a/js/src/cli/add.ts b/js/src/cli/add.ts index 6c8dd7fdd8..27f385f39c 100644 --- a/js/src/cli/add.ts +++ b/js/src/cli/add.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; import { Composio } from "../sdk"; @@ -15,29 +16,37 @@ export default class AddCommand { .description("Add a new app") .argument("", "The name of the app") .option("-f, --force", "Force the connection setup") - .option("--skip-default-connector", "Skip the default connector auth prompt") + .option( + "--skip-default-connector", + "Skip the default connector auth prompt" + ) .action(this.handleAction.bind(this)); } private async handleAction( appName: string, - options: { force?: boolean, skipDefaultConnector?: boolean }, + options: { force?: boolean; skipDefaultConnector?: boolean } ): Promise { const composioClient = new Composio(); - let integration: GetConnectorListResDTO | undefined = + const integration: GetConnectorListResDTO | undefined = await composioClient.integrations.list({ // @ts-ignore appName: appName.toLowerCase(), }); let firstIntegration: GetConnectorInfoResDTO | undefined; - if (integration?.items?.length === 0 || options.force || options.skipDefaultConnector) { + if ( + integration?.items?.length === 0 || + options.force || + options.skipDefaultConnector + ) { firstIntegration = (await this.createIntegration( appName, - options.skipDefaultConnector, + options.skipDefaultConnector )) as GetConnectorInfoResDTO; - }else{ - firstIntegration = (integration as GetConnectorListResDTO)?.items[0] as GetConnectorInfoResDTO; + } else { + firstIntegration = (integration as GetConnectorListResDTO) + ?.items[0] as GetConnectorInfoResDTO; } if (!firstIntegration) { console.log(chalk.red("No integration found or created")); @@ -50,7 +59,7 @@ export default class AddCommand { }); if (connection.items.length > 0 && !options.force) { - await this.shouldForceConnectionSetup() + await this.shouldForceConnectionSetup(); } // @ts-ignore @@ -60,22 +69,25 @@ export default class AddCommand { async shouldForceConnectionSetup() { const { shouldForce } = await inquirer.prompt([ { - type: 'confirm', - name: 'shouldForce', - message: 'A connection already exists. Do you want to force a new connection?', + type: "confirm", + name: "shouldForce", + message: + "A connection already exists. Do you want to force a new connection?", default: false, }, ]); if (!shouldForce) { - console.log(chalk.yellow('Operation cancelled. Existing connection will be used.')); + console.log( + chalk.yellow("Operation cancelled. Existing connection will be used.") + ); process.exit(0); } } private async waitUntilConnected( connectedAccountId: string, - timeout: number = 30000, + timeout: number = 30000 ): Promise { const composioClient = new Composio(); const startTime = Date.now(); @@ -98,7 +110,7 @@ export default class AddCommand { } throw new Error( - `Connection did not become active within ${timeout / 1000} seconds`, + `Connection did not become active within ${timeout / 1000} seconds` ); } @@ -107,9 +119,10 @@ export default class AddCommand { const data = await composioClient.integrations.get({ integrationId }); const { expectedInputFields } = data!; - - - const config = await this.collectInputFields(expectedInputFields as any , true); + const config = await this.collectInputFields( + expectedInputFields as any, + true + ); const connectionData = await composioClient.connectedAccounts.create({ integrationId, @@ -123,7 +136,7 @@ export default class AddCommand { if (connectionData.redirectUrl) { console.log( chalk.white("Redirecting to the app"), - chalk.blue(connectionData.redirectUrl), + chalk.blue(connectionData.redirectUrl) ); open(connectionData.redirectUrl); @@ -134,23 +147,34 @@ export default class AddCommand { } } - private async createIntegration(appName: string , skipDefaultConnectorAuth: boolean = false) { + private async createIntegration( + appName: string, + skipDefaultConnectorAuth: boolean = false + ) { const composioClient = new Composio(); const app = await composioClient.apps.get({ appKey: appName.toLowerCase(), }); if (app.no_auth) { - console.log(chalk.green(`The app '${appName}' does not require authentication. You can connect it directly.\n`)); - process.exit(0); + console.log( + chalk.green( + `The app '${appName}' does not require authentication. You can connect it directly.\n` + ) + ); + process.exit(0); } const testConnectors = app.testConnectors || []; - + const config: Record = {}; let useComposioAuth = true; - if (!app.no_auth && testConnectors.length > 0 && !skipDefaultConnectorAuth) { + if ( + !app.no_auth && + testConnectors.length > 0 && + !skipDefaultConnectorAuth + ) { const { doYouWantToUseComposioAuth } = await inquirer.prompt({ type: "confirm", name: "doYouWantToUseComposioAuth", @@ -159,7 +183,7 @@ export default class AddCommand { useComposioAuth = doYouWantToUseComposioAuth; } - if(skipDefaultConnectorAuth){ + if (skipDefaultConnectorAuth) { useComposioAuth = false; } @@ -180,16 +204,30 @@ export default class AddCommand { if (useComposioAuth) { useComposioAuth = true; - return this.setupIntegration(app, authSchema, useComposioAuth, config, integrationName); + return this.setupIntegration( + app, + authSchema, + useComposioAuth, + config, + integrationName + ); } - console.log("\n\nWe'll require you to enter the credentials for the app manually.\n\n"); + console.log( + "\n\nWe'll require you to enter the credentials for the app manually.\n\n" + ); const authConfig = await this.collectInputFields( // @ts-ignore - app.auth_schemes[0].fields, + app.auth_schemes[0].fields + ); + return this.setupIntegration( + app, + authSchema, + useComposioAuth, + authConfig, + integrationName ); - return this.setupIntegration(app, authSchema, useComposioAuth, authConfig, integrationName); } async collectInputFields( @@ -201,7 +239,7 @@ export default class AddCommand { required: boolean; type: string; }[], - isConnection = false, + isConnection = false ): Promise> { const config: Record = {}; @@ -229,7 +267,7 @@ export default class AddCommand { authMode: any, useComposioAuth: boolean, config: Record, - name: string, + name: string ) { const composioClient = new Composio(); const integration = await composioClient.integrations.create({ @@ -239,8 +277,7 @@ export default class AddCommand { name, authConfig: config, }); - return integration; } -} \ No newline at end of file +} diff --git a/js/src/cli/apps.ts b/js/src/cli/apps.ts index 0664da1365..2c3fe1f7de 100644 --- a/js/src/cli/apps.ts +++ b/js/src/cli/apps.ts @@ -1,13 +1,18 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; import { getOpenAPIClient } from "../sdk/utils/config"; import client from "../sdk/client/client"; -// @ts-ignore import resolvePackagePath from "resolve-package-path"; import fs from "fs"; import path from "path"; + +type ErrorWithMessage = { + message: string; +}; + export default class AppsCommand { private program: Command; @@ -33,7 +38,7 @@ export default class AppsCommand { console.log(app.key); } } catch (error) { - console.log(chalk.red((error as any).message)); + console.log(chalk.red((error as ErrorWithMessage).message)); return; } } @@ -52,7 +57,7 @@ class AppUpdateCommand { async updateActionsAndAppList( appList: string, - actionsList: string, + actionsList: string ): Promise { try { const constantPath = resolvePackagePath("composio-core", process.cwd()); @@ -65,18 +70,18 @@ class AppUpdateCommand { if (fileNamePath.includes("cli/index.ts")) { constantFilePath = path.join( "/Users/himanshu/Desktop/composio/composio/js" as string, - "./lib/src/constants.js", + "./lib/src/constants.js" ); } else { // if package is used then we need to update the constants file in the package folder constantFilePath = path.join( constantPath as string, - "../lib/src/constants.js", + "../lib/src/constants.js" ); } } catch (e) { console.log(chalk.red("Error while updating constants file")); - console.log(chalk.red((e as any).message)); + console.log(chalk.red((e as ErrorWithMessage).message)); } const constantFile = fs.readFileSync(constantFilePath, "utf8"); @@ -84,22 +89,22 @@ class AppUpdateCommand { const updatedConstantFile = constantFile .replace( /\/\/ apps list start here[\s\S]*?\/\/ apps list end here/, - `// apps list start here\n${appList}// apps list end here`, + `// apps list start here\n${appList}// apps list end here` ) .replace( /\/\/ actions list start here[\s\S]*?\/\/ actions list end here/, - `// actions list start here\n ${actionsList}\n // actions list end here`, + `// actions list start here\n ${actionsList}\n // actions list end here` ); fs.writeFileSync(constantFilePath, updatedConstantFile); console.log( chalk.green("Constants file updated successfully"), - chalk.green(constantFilePath), + chalk.green(constantFilePath) ); } catch (e) { console.log(chalk.red("Error while updating constants file")); - console.log(chalk.red((e as any).message)); + console.log(chalk.red((e as ErrorWithMessage).message)); } } @@ -112,20 +117,19 @@ class AppUpdateCommand { (res) => res.data?.items .map((app) => `'${app.key.toUpperCase()}': '${app.key}'`) - .join(",\n") || [], - ); - const actionsList = await client.actionsV2.listActionsMinimalV2({}) - .then( - (res) => - res.data?.items - // @ts-ignore - .map((action) => `'${action.name}': '${action.enum}'`) - .join(",\n") || [], + .join(",\n") || [] ); + const actionsList = await client.actionsV2.listActionsMinimalV2({}).then( + (res) => + res.data?.items + // @ts-ignore + .map((action) => `'${action.name}': '${action.enum}'`) + .join(",\n") || [] + ); await this.updateActionsAndAppList( appList as string, - actionsList as string, + actionsList as string ); } } diff --git a/js/src/cli/connections.ts b/js/src/cli/connections.ts index 8e11dcc44f..cfe4cf7d63 100644 --- a/js/src/cli/connections.ts +++ b/js/src/cli/connections.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; @@ -35,10 +36,10 @@ export default class ConnectionsCommand { for (const connection of data?.items || []) { console.log(chalk.cyan(`• ${chalk.bold("Id")}: ${connection.id}`)); console.log( - chalk.magenta(` ${chalk.bold("App")}: ${connection.appName}`), + chalk.magenta(` ${chalk.bold("App")}: ${connection.appName}`) ); console.log( - chalk.yellow(` ${chalk.bold("Status")}: ${connection.status}`), + chalk.yellow(` ${chalk.bold("Status")}: ${connection.status}`) ); console.log(""); // Add an empty line for better readability between connections } @@ -71,7 +72,7 @@ export class ConnectionsGetCommand { for (const [key, value] of Object.entries(data as Record)) { console.log( - `- ${chalk.cyan.bold(key)}: ${JSON.stringify(value, null, 2)}`, + `- ${chalk.cyan.bold(key)}: ${JSON.stringify(value, null, 2)}` ); } } diff --git a/js/src/cli/index.ts b/js/src/cli/index.ts index 392222251f..8e6bb08388 100644 --- a/js/src/cli/index.ts +++ b/js/src/cli/index.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ // Node Imports import { Command } from "commander"; import chalk from "chalk"; @@ -39,13 +40,13 @@ program.addHelpText("before", (options) => { formatLine(""), formatLine(` ${chalk.bold("📚 Commands:")}\n`), ...options.command.commands.map((cmd) => - formatLine(` ${chalk.cyanBright(cmd.name())} - ${cmd.description()}`), + formatLine(` ${chalk.cyanBright(cmd.name())} - ${cmd.description()}`) ), formatLine(` ${chalk.cyan("help")} - Display help for command`), formatLine(""), formatLine(` ${chalk.bold("⚙️ Options:")}\n`), formatLine( - ` ${chalk.magenta("-h, --help")} ℹ️ Display help for command`, + ` ${chalk.magenta("-h, --help")} ℹ️ Display help for command` ), formatLine(""), ].join("\n"); diff --git a/js/src/cli/integrations.ts b/js/src/cli/integrations.ts index 90f925b63c..ebc0c1aa5c 100644 --- a/js/src/cli/integrations.ts +++ b/js/src/cli/integrations.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; @@ -35,12 +36,12 @@ export default class ConnectionsCommand { const typedIntegration = integration as Record; console.log(chalk.cyan(`• ${chalk.bold("Id")}: ${typedIntegration.id}`)); console.log( - chalk.magenta(` ${chalk.bold("App")}: ${typedIntegration.appName}`), + chalk.magenta(` ${chalk.bold("App")}: ${typedIntegration.appName}`) ); console.log( chalk.magenta( - ` ${chalk.bold("Created At")}: ${parseDate(typedIntegration.createdAt)}`, - ), + ` ${chalk.bold("Created At")}: ${parseDate(typedIntegration.createdAt)}` + ) ); console.log(""); // Add an empty line for better readability between connections } diff --git a/js/src/cli/login.ts b/js/src/cli/login.ts index 06ab99fc0c..9ee820c804 100644 --- a/js/src/cli/login.ts +++ b/js/src/cli/login.ts @@ -1,12 +1,10 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; import inquirer from "inquirer"; import open from "open"; -import { - getSDKConfig, - getOpenAPIClient, -} from "../sdk/utils/config"; +import { getSDKConfig, getOpenAPIClient } from "../sdk/utils/config"; import client from "../sdk/client/client"; import { FRONTEND_BASE_URL } from "./src/constants"; import { setCliConfig } from "../sdk/utils/cli"; @@ -20,7 +18,7 @@ export default class LoginCommand { .command("login") .option( "-n, --no-browser", - "No browser will be opened, you will have to manually copy the link and paste it in your browser", + "No browser will be opened, you will have to manually copy the link and paste it in your browser" ) .description("Authenticate and login to Composio") .action(this.handleAction.bind(this)); @@ -33,8 +31,8 @@ export default class LoginCommand { if (apiKey) { console.log( chalk.yellow( - "✨ You are already authenticated and ready to use Composio! ✨\n", - ), + "✨ You are already authenticated and ready to use Composio! ✨\n" + ) ); return; } @@ -45,7 +43,7 @@ export default class LoginCommand { const cliKey = data?.key as string; const loginUrl = `${FRONTEND_BASE_URL}?cliKey=${cliKey}`; - + this.displayLoginInstructions(loginUrl, options.browser); const authCode = await this.promptForAuthCode(); await this.verifyAndSetupCli(cliKey, authCode, baseURL); @@ -75,7 +73,7 @@ export default class LoginCommand { private async verifyAndSetupCli( cliKey: string, authCode: string, - baseURL: string, + baseURL: string ): Promise { const { data, error } = await client.cli.verifyCliCode({ query: { key: cliKey, code: authCode }, @@ -90,7 +88,7 @@ export default class LoginCommand { setCliConfig(apiKeyFromServer as string, ""); console.log( - chalk.yellow("✨ You are authenticated and ready to use Composio! ✨\n"), + chalk.yellow("✨ You are authenticated and ready to use Composio! ✨\n") ); } } diff --git a/js/src/cli/logout.ts b/js/src/cli/logout.ts index c5cf4efd35..7013170646 100644 --- a/js/src/cli/logout.ts +++ b/js/src/cli/logout.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; import { setCliConfig } from "../sdk/utils/cli"; @@ -16,7 +17,7 @@ export default class LogoutCommand { private handleAction(): void { setCliConfig("", ""); console.log( - chalk.yellow("✨ You have been logged out from Composio! ✨\n"), + chalk.yellow("✨ You have been logged out from Composio! ✨\n") ); } } diff --git a/js/src/cli/src/util.ts b/js/src/cli/src/util.ts index dd609311cc..640c069f6e 100644 --- a/js/src/cli/src/util.ts +++ b/js/src/cli/src/util.ts @@ -8,7 +8,7 @@ export function getArgs(args: string[] = []) { acc[key] = value[index]; return acc; }, - {} as Record, + {} as Record ); } diff --git a/js/src/cli/triggers.ts b/js/src/cli/triggers.ts index 00c8cde445..162383a280 100644 --- a/js/src/cli/triggers.ts +++ b/js/src/cli/triggers.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; @@ -65,15 +66,15 @@ export default class ConnectionsCommand { const typedTrigger = trigger as any; console.log( chalk.cyan(` ${chalk.bold("Name")}:`), - chalk.white(typedTrigger.appName), + chalk.white(typedTrigger.appName) ); console.log( chalk.cyan(` ${chalk.bold("Enum")}:`), - chalk.white(typedTrigger.enum), + chalk.white(typedTrigger.enum) ); console.log( chalk.cyan(` ${chalk.bold("Description")}:`), - chalk.white(typedTrigger.description), + chalk.white(typedTrigger.description) ); console.log(""); // Add an empty line for better readability between triggers } @@ -98,7 +99,7 @@ export class TriggerAdd { const data = (await composioClient.triggers.list()).find( // @ts-ignore - (trigger) => trigger.enum.toLowerCase() === triggerName.toLowerCase(), + (trigger) => trigger.enum.toLowerCase() === triggerName.toLowerCase() ); if (!data) { @@ -115,7 +116,7 @@ export class TriggerAdd { if (!connection) { console.log(chalk.red(`Connection to app ${appName} not found`)); console.log( - `Connect to the app by running: ${chalk.cyan(`composio add ${appName}`)}`, + `Connect to the app by running: ${chalk.cyan(`composio add ${appName}`)}` ); return; } @@ -138,13 +139,17 @@ export class TriggerAdd { } } - const triggerSetupData = await composioClient.triggers.setup({ + const triggerSetupData = await composioClient.triggers.setup({ connectedAccountId: connection.id, triggerName, config: configValue, }); - console.log(chalk.green(`Trigger ${triggerName} setup to app ${appName} with id ${triggerSetupData?.triggerId}`)); + console.log( + chalk.green( + `Trigger ${triggerName} setup to app ${appName} with id ${triggerSetupData?.triggerId}` + ) + ); } } @@ -173,7 +178,7 @@ export class TriggerDisable { export class ActiveTriggers { private program: Command; - constructor(program: Command,register: boolean = true) { + constructor(program: Command, register: boolean = true) { this.program = program; if (register) { @@ -191,7 +196,7 @@ export class ActiveTriggers { console.log(`Id: ${chalk.bold(trigger.id)}`); console.log(`Trigger Name: ${chalk.cyan(trigger.triggerName)}`); console.log( - `TriggerConfig: ${chalk.magenta(JSON.stringify(trigger.triggerConfig, null, 2))}`, + `TriggerConfig: ${chalk.magenta(JSON.stringify(trigger.triggerConfig, null, 2))}` ); console.log(`Connection ID: ${chalk.yellow(trigger.connectionId)}`); console.log(""); // Add an empty line for better readability between triggers diff --git a/js/src/cli/whoami.ts b/js/src/cli/whoami.ts index ca94f08890..03d5eb2668 100644 --- a/js/src/cli/whoami.ts +++ b/js/src/cli/whoami.ts @@ -1,3 +1,4 @@ +/* eslint-disable no-console */ import chalk from "chalk"; import { Command } from "commander"; import { getSDKConfig } from "../sdk/utils/config"; @@ -19,8 +20,8 @@ export default class WhoamiCommand { if (!apiKey) { console.log( chalk.red( - "You are not authenticated. Please run `composio login` to authenticate.", - ), + "You are not authenticated. Please run `composio login` to authenticate." + ) ); return; } @@ -28,7 +29,7 @@ export default class WhoamiCommand { console.log(`\n🔑 API Key: ${chalk.cyan(apiKey)}`); console.log(`🌐 Base URL: ${chalk.cyan(baseURL)}`); console.log( - `${chalk.yellow("✨")} You are authenticated and ready to use Composio! ${chalk.yellow("✨")} \n`, + `${chalk.yellow("✨")} You are authenticated and ready to use Composio! ${chalk.yellow("✨")} \n` ); } } diff --git a/js/src/constants.js b/js/src/constants.js index 50d5ae0c95..157d1e86ad 100644 --- a/js/src/constants.js +++ b/js/src/constants.js @@ -1,19 +1,17 @@ const APPS = { - // apps list start here - - // apps list end here -} + // apps list start here + // apps list end here +}; const ACTIONS = { - // actions list start here - - // actions list end here -} + // actions list start here + // actions list end here +}; -const COMPOSIO_VERSION = `0.2.4` +const COMPOSIO_VERSION = `0.3.0`; module.exports = { - APPS, - ACTIONS, - COMPOSIO_VERSION -} \ No newline at end of file + APPS, + ACTIONS, + COMPOSIO_VERSION, +}; diff --git a/js/src/constants.ts b/js/src/constants.ts new file mode 100644 index 0000000000..a83883627a --- /dev/null +++ b/js/src/constants.ts @@ -0,0 +1,11 @@ +const APPS = { + // apps list start here + // apps list end here +}; + +const ACTIONS = { + // actions list start here + // actions list end here +}; + +export { APPS, ACTIONS }; diff --git a/js/src/env/base.ts b/js/src/env/base.ts index 4194202c64..4436a36d94 100644 --- a/js/src/env/base.ts +++ b/js/src/env/base.ts @@ -10,217 +10,239 @@ const ENV_COMPOSIO_API_KEY = "COMPOSIO_API_KEY"; const ENV_COMPOSIO_BASE_URL = "COMPOSIO_BASE_URL"; function _readEnvVar(name: string, defaultValue: string | null): string { - const value = getEnvVariable(name, defaultValue!) || defaultValue; - if (value === undefined) { - throw new Error(`Please provide value for \`${name}\``); - } - return value as string; + const value = getEnvVariable(name, defaultValue!) || defaultValue; + if (value === undefined) { + throw new Error(`Please provide value for \`${name}\``); + } + return value as string; } class Shell { - private _id: string; + private _id: string; - constructor() { - this._id = uuidv4(); - } + constructor() { + this._id = uuidv4(); + } - sanitizeCommand(cmd: string): string { - return `${cmd.trim()}\n`; - } + sanitizeCommand(cmd: string): string { + return `${cmd.trim()}\n`; + } - toString(): string { - return `Shell(type=${this.constructor.name}, id=${this.id})`; - } + toString(): string { + return `Shell(type=${this.constructor.name}, id=${this.id})`; + } - get id(): string { - return this._id; - } + get id(): string { + return this._id; + } - setup(): void { - throw new Error("Method 'setup()' must be implemented."); - } + setup(): void { + throw new Error("Method 'setup()' must be implemented."); + } - exec(cmd: string): void { - throw new Error("Method 'exec()' must be implemented."); - } + exec(cmd: string): void { + throw new Error("Method 'exec()' must be implemented."); + } - stop(): void { - throw new Error("Method 'stop()' must be implemented."); - } + stop(): void { + throw new Error("Method 'stop()' must be implemented."); + } } export class ShellFactory { - private _factory: () => Shell; - private _recent: Shell | null; - private _shells: { [key: string]: Shell }; - - constructor(factory: () => Shell) { - this._factory = factory; - this._recent = null; - this._shells = {}; - } - - get recent(): Shell { - return this._recent || this.new(); - } - - set recent(shell: Shell) { - this._recent = shell; - } - - new(): Shell { - const shell = this._factory(); - shell.setup(); - this._shells[shell.id] = shell; - this.recent = shell; - return shell; - } - - get(id: string | null = null): Shell { - if (!id) { - return this.recent; - } - if (!this._shells[id]) { - throw new Error(`No shell found with ID: ${id}`); - } - const shell = this._shells[id]; - this.recent = shell; - return shell; - } - - exec(cmd: string, id: string | null = null): void { - return this.get(id).exec(cmd); - } - - stop(id: string): void { - if (!this._shells[id]) { - return; - } - const shell = this._shells[id]; - shell.stop(); - delete this._shells[id]; - } - - teardown(): void { - Object.keys(this._shells).forEach(id => { - this._shells[id].stop(); - delete this._shells[id]; - }); - this._recent = null; - } + private _factory: () => Shell; + private _recent: Shell | null; + private _shells: { [key: string]: Shell }; + + constructor(factory: () => Shell) { + this._factory = factory; + this._recent = null; + this._shells = {}; + } + + get recent(): Shell { + return this._recent || this.new(); + } + + set recent(shell: Shell) { + this._recent = shell; + } + + new(): Shell { + const shell = this._factory(); + shell.setup(); + this._shells[shell.id] = shell; + this.recent = shell; + return shell; + } + + get(id: string | null = null): Shell { + if (!id) { + return this.recent; + } + if (!this._shells[id]) { + throw new Error(`No shell found with ID: ${id}`); + } + const shell = this._shells[id]; + this.recent = shell; + return shell; + } + + exec(cmd: string, id: string | null = null): void { + return this.get(id).exec(cmd); + } + + stop(id: string): void { + if (!this._shells[id]) { + return; + } + const shell = this._shells[id]; + shell.stop(); + delete this._shells[id]; + } + + teardown(): void { + Object.keys(this._shells).forEach((id) => { + this._shells[id].stop(); + delete this._shells[id]; + }); + this._recent = null; + } } export interface IExecuteActionMetadata { - entityId?: string | null; + entityId?: string | null; } export class Workspace { - id: string; - accessToken: string; - composioAPIKey: string; - composioBaseURL: string; - githubAccessToken: string; - environment: { [key: string]: string }; - private _shell_factory: ShellFactory | undefined; - - constructor(configRepo: WorkspaceConfig) { - this.id = uuidv4(); - this.accessToken = uuidv4().replace(/-/g, ""); - this.composioAPIKey = _readEnvVar(ENV_COMPOSIO_API_KEY, configRepo.config.composioAPIKey!); - this.composioBaseURL = _readEnvVar(ENV_COMPOSIO_BASE_URL, configRepo.config.composioBaseURL!) + (configRepo.config.composioBaseURL!.endsWith('/api') ? '' : '/api'); - this.githubAccessToken = configRepo.config.githubAccessToken || getEnvVariable(ENV_GITHUB_ACCESS_TOKEN, "NO_VALUE")!; - this.environment = { - ...(configRepo.config.environment || {}), - [ENV_COMPOSIO_API_KEY]: this.composioAPIKey, - [ENV_COMPOSIO_BASE_URL]: this.composioBaseURL, - [ENV_GITHUB_ACCESS_TOKEN]: this.githubAccessToken, - [`_COMPOSIO_${ENV_GITHUB_ACCESS_TOKEN}`]: this.githubAccessToken, - [ENV_ACCESS_TOKEN]: this.accessToken - }; - } - - toString(): string { - return `Workspace(type=${this.constructor.name}, id=${this.id})`; - } - - setup(): void { - throw new Error("Method 'setup()' must be implemented."); - } - - get shells(): ShellFactory { - if (!this._shell_factory) { - this._shell_factory = new ShellFactory(() => this._createShell()); - } - return this._shell_factory; - } - - _createShell(): Shell { - throw new Error("Method '_create_shell()' must be implemented."); - } - - executeAction(action: any, request_data: any, metadata: IExecuteActionMetadata = {}): Promise> { - throw new Error("Method 'execute_action()' must be implemented."); - } - - teardown(): void { - this.shells.teardown(); - } + id: string; + accessToken: string; + composioAPIKey: string; + composioBaseURL: string; + githubAccessToken: string; + environment: { [key: string]: string }; + private _shell_factory: ShellFactory | undefined; + + constructor(configRepo: WorkspaceConfig) { + this.id = uuidv4(); + this.accessToken = uuidv4().replace(/-/g, ""); + this.composioAPIKey = _readEnvVar( + ENV_COMPOSIO_API_KEY, + configRepo.config.composioAPIKey! + ); + this.composioBaseURL = + _readEnvVar(ENV_COMPOSIO_BASE_URL, configRepo.config.composioBaseURL!) + + (configRepo.config.composioBaseURL!.endsWith("/api") ? "" : "/api"); + this.githubAccessToken = + configRepo.config.githubAccessToken || + getEnvVariable(ENV_GITHUB_ACCESS_TOKEN, "NO_VALUE")!; + this.environment = { + ...(configRepo.config.environment || {}), + [ENV_COMPOSIO_API_KEY]: this.composioAPIKey, + [ENV_COMPOSIO_BASE_URL]: this.composioBaseURL, + [ENV_GITHUB_ACCESS_TOKEN]: this.githubAccessToken, + [`_COMPOSIO_${ENV_GITHUB_ACCESS_TOKEN}`]: this.githubAccessToken, + [ENV_ACCESS_TOKEN]: this.accessToken, + }; + } + + toString(): string { + return `Workspace(type=${this.constructor.name}, id=${this.id})`; + } + + setup(): void { + throw new Error("Method 'setup()' must be implemented."); + } + + get shells(): ShellFactory { + if (!this._shell_factory) { + this._shell_factory = new ShellFactory(() => this._createShell()); + } + return this._shell_factory; + } + + _createShell(): Shell { + throw new Error("Method '_create_shell()' must be implemented."); + } + + executeAction( + action: any, + request_data: any, + metadata: IExecuteActionMetadata = {} + ): Promise> { + throw new Error("Method 'execute_action()' must be implemented."); + } + + teardown(): void { + this.shells.teardown(); + } } export class RemoteWorkspace extends Workspace { - url: string; - - constructor(configRepo: WorkspaceConfig) { - super(configRepo); - this.url = configRepo.config.composioBaseURL! + (configRepo.config.composioBaseURL!.endsWith('/api') ? '' : '/api'); - } - - async _request(endpoint: string, method: string, json: any = null, timeout: number = 60000.0): Promise { - return axios({ - url: `${this.url}${endpoint}`, - method: method, - data: json, - headers: { - "x-api-key": this.accessToken - }, - timeout: timeout - }); - } - - _createShell(): Shell { - throw new Error("Creating shells for remote workspaces is not allowed."); - } - - _upload(action: any): void { - throw new Error("Method '_upload()' must be implemented."); - } - - async getLocalActionsSchema(): Promise { - const request = await this._request("/local_actions", "get"); - return (request.data as IPythonActionDetails).data; - } - - async executeAction(action: string, request_data: any, metadata: IExecuteActionMetadata = {}): Promise { - if (!metadata.entityId) { - metadata.entityId = "default"; - } - const request = await this._request(`/actions/execute/${action}`, "post", { - params: request_data, - entity_id: metadata.entityId, - metadata: metadata - }); - const response = request.data; - - if (!response.error) { - return response.data; - } - if (response.error?.includes("Invalid value")) { - return { - status: "NOT_FOUND", - error: `Action ${action} does not exist or supported.`, - instructions: `Please only refer to the tools you have access to` - } - } - throw new Error(`Error while executing ${action}: ${response.error}`); - } + url: string; + + constructor(configRepo: WorkspaceConfig) { + super(configRepo); + this.url = + configRepo.config.composioBaseURL! + + (configRepo.config.composioBaseURL!.endsWith("/api") ? "" : "/api"); + } + + async _request( + endpoint: string, + method: string, + json: any = null, + timeout: number = 60000.0 + ): Promise { + return axios({ + url: `${this.url}${endpoint}`, + method: method, + data: json, + headers: { + "x-api-key": this.accessToken, + }, + timeout: timeout, + }); + } + + _createShell(): Shell { + throw new Error("Creating shells for remote workspaces is not allowed."); + } + + _upload(action: any): void { + throw new Error("Method '_upload()' must be implemented."); + } + + async getLocalActionsSchema(): Promise { + const request = await this._request("/local_actions", "get"); + return (request.data as IPythonActionDetails).data; + } + + async executeAction( + action: string, + request_data: any, + metadata: IExecuteActionMetadata = {} + ): Promise { + if (!metadata.entityId) { + metadata.entityId = "default"; + } + const request = await this._request(`/actions/execute/${action}`, "post", { + params: request_data, + entity_id: metadata.entityId, + metadata: metadata, + }); + const response = request.data; + + if (!response.error) { + return response.data; + } + if (response.error?.includes("Invalid value")) { + return { + status: "NOT_FOUND", + error: `Action ${action} does not exist or supported.`, + instructions: `Please only refer to the tools you have access to`, + }; + } + throw new Error(`Error while executing ${action}: ${response.error}`); + } } diff --git a/js/src/env/config.ts b/js/src/env/config.ts index ed443cf0bf..c96c420269 100644 --- a/js/src/env/config.ts +++ b/js/src/env/config.ts @@ -1,18 +1,20 @@ import { ExecEnv } from "./factory"; export interface IWorkspaceConfig { - composioAPIKey?: string | null; - composioBaseURL?: string | null; - githubAccessToken?: string | null; - environment?: { [key: string]: string }; -}; + composioAPIKey?: string | null; + composioBaseURL?: string | null; + githubAccessToken?: string | null; + environment?: { [key: string]: string }; +} -export class WorkspaceConfig { - env: ExecEnv; - config: TConfig; +export class WorkspaceConfig< + TConfig extends IWorkspaceConfig = IWorkspaceConfig, +> { + env: ExecEnv; + config: TConfig; - constructor(env: ExecEnv, config: TConfig) { - this.config = config; - this.env = env; - } -} \ No newline at end of file + constructor(env: ExecEnv, config: TConfig) { + this.config = config; + this.env = env; + } +} diff --git a/js/src/env/docker/workspace.ts b/js/src/env/docker/workspace.ts index a710456920..a394d73de9 100644 --- a/js/src/env/docker/workspace.ts +++ b/js/src/env/docker/workspace.ts @@ -12,220 +12,235 @@ const DEFAULT_IMAGE = "composio/composio"; const DEFAULT_PORT = 54321; function getFreePort(): Promise { - return new Promise((resolve, reject) => { - const server = require("node:net").createServer(); - server.unref(); - server.on("error", reject); - server.listen(0, () => { - const port = server.address().port; - server.close(() => resolve(port)); - }); + return new Promise((resolve, reject) => { + const server = require("node:net").createServer(); + server.unref(); + server.on("error", reject); + server.listen(0, () => { + const port = server.address().port; + server.close(() => resolve(port)); }); + }); } export interface IDockerConfig extends IWorkspaceConfig { - /** Name of the docker image. */ - image?: string; - - /** - * Ports to bind inside the container - * - * Note: port 8000 is reserved for the tooling server inside the container - */ - ports?: { [key: number]: any }; - - /** Volumes to bind inside the container */ - volumes?: { [key: string]: any }; + /** Name of the docker image. */ + image?: string; + + /** + * Ports to bind inside the container + * + * Note: port 8000 is reserved for the tooling server inside the container + */ + ports?: { [key: number]: any }; + + /** Volumes to bind inside the container */ + volumes?: { [key: string]: any }; } export class DockerWorkspace extends RemoteWorkspace { - public docker: Docker; - public container: any | null = null; - public id: string; - public port: number = DEFAULT_PORT; - public image: string; - public url: string = ""; - - private _ports?: IDockerConfig["ports"] - private _volumes?: IDockerConfig["volumes"] - - constructor(configRepo: WorkspaceConfig) { - super(configRepo); - this.id = `composio-${uuidv4()}`; - this.image = getEnvVariable(ENV_COMPOSIO_SWE_AGENT, DEFAULT_IMAGE)!; - this.docker = nodeExternalRequire("dockerode")(); - this._ports = configRepo.config.ports; - this._volumes = configRepo.config.volumes; + public docker: Docker; + public container: any | null = null; + public id: string; + public port: number = DEFAULT_PORT; + public image: string; + public url: string = ""; + + private _ports?: IDockerConfig["ports"]; + private _volumes?: IDockerConfig["volumes"]; + + constructor(configRepo: WorkspaceConfig) { + super(configRepo); + this.id = `composio-${uuidv4()}`; + this.image = getEnvVariable(ENV_COMPOSIO_SWE_AGENT, DEFAULT_IMAGE)!; + this.docker = nodeExternalRequire("dockerode")(); + this._ports = configRepo.config.ports; + this._volumes = configRepo.config.volumes; + } + + private getBaseDockerConfig() { + const IS_DEV_MODE = getEnvVariable(ENV_COMPOSIO_DEV_MODE, "0"); + + const exposedPorts: { [key: string]: {} } = { + "8000/tcp": {}, + }; + const portBindings: { [key: string]: Array<{ HostPort: string }> } = { + "8000/tcp": [ + { + HostPort: this.port.toString(), + }, + ], + }; + + // Add additional ports if specified in the environment configuration + if (this._ports) { + for (const port of Object.keys(this._ports)) { + const portKey = `${port}/tcp`; + exposedPorts[portKey] = {}; + portBindings[portKey] = [{ HostPort: port }]; + } } - private getBaseDockerConfig() { - const IS_DEV_MODE = getEnvVariable(ENV_COMPOSIO_DEV_MODE, "0"); - - const exposedPorts: {[key: string]: {}} = { - "8000/tcp": {}, - }; - const portBindings: {[key: string]: Array<{ HostPort: string }>} = { - "8000/tcp": [ - { - HostPort: this.port.toString(), - }, - ], - }; - - // Add additional ports if specified in the environment configuration - if (this._ports) { - for (const port of Object.keys(this._ports)) { - const portKey = `${port}/tcp`; - exposedPorts[portKey] = {}; - portBindings[portKey] = [{ HostPort: port }]; - } - } - - const volumeBindings: Array = []; - - // Add additional volumes if specified in the environment configuration - if (this._volumes) { - for (const hostPath in this._volumes) { - const containerPath = this._volumes[hostPath]; - volumeBindings.push(`${hostPath}:${containerPath}`); - } - } - - if(IS_DEV_MODE === "1") { - const path = require("node:path"); - const os = require("node:os"); + const volumeBindings: Array = []; - const COMPOSIO_PATH = path.resolve(__dirname, "../../../../python/"); - const COMPOSIO_CACHE = path.join(os.homedir(), ".composio"); - - volumeBindings.push(...[ - `${COMPOSIO_PATH}:/opt/composio-core:rw`, - `${COMPOSIO_CACHE}:/root/.composio:rw`, - ]); - } + // Add additional volumes if specified in the environment configuration + if (this._volumes) { + for (const hostPath in this._volumes) { + const containerPath = this._volumes[hostPath]; + volumeBindings.push(`${hostPath}:${containerPath}`); + } + } - const envBindings: Array = Object.entries(this.environment).map( - ([key, value]) => `${key}=${value}` - ); + if (IS_DEV_MODE === "1") { + const path = require("node:path"); + const os = require("node:os"); - if(IS_DEV_MODE === "1") { - envBindings.push(`${ENV_COMPOSIO_DEV_MODE}=1`); - } + const COMPOSIO_PATH = path.resolve(__dirname, "../../../../python/"); + const COMPOSIO_CACHE = path.join(os.homedir(), ".composio"); - return { exposedPorts, portBindings, volumeBindings, envBindings }; + volumeBindings.push( + ...[ + `${COMPOSIO_PATH}:/opt/composio-core:rw`, + `${COMPOSIO_CACHE}:/root/.composio:rw`, + ] + ); } - async setup() { - this.port = await getFreePort(); - this.url = `http://localhost:${this.port}/api`; - - const images = await this.docker.listImages(); - const imageExists = images.some((image: any) => image.RepoTags && image.RepoTags.find((tag: any) => tag.startsWith(this.image))); - - - if (!imageExists) { - logger.debug(`Pulling Docker image ${this.image}...`); - let cliProgress = nodeExternalRequire("cli-progress"); - - const bar: CliProgress.Bar = new cliProgress.SingleBar({ - format: '{bar} | {percentage}% | {status}', - hideCursor: true - }, cliProgress.Presets.shades_classic); - - bar.start(100, 0, { status: 'Initializing...' }); - bar.update({ status: `Image ${this.image} not found locally. Pulling from Docker Hub...` }); - await new Promise((resolve, reject) => { - this.docker.pull(this.image, (err: any, stream: any) => { - if (err) { - bar.stop(); - logger.error('Failed to pull Docker image.'); - return reject(err); - } - this.docker.modem.followProgress(stream, onFinished, onProgress); - - function onFinished(err: any, output: any) { - if (err) { - bar.stop(); - logger.error('Failed to pull Docker image.'); - return reject(err); - } - bar.update(100, { status: 'Docker image pulled successfully.' }); - bar.stop(); - resolve(output); - } - - function onProgress(event: any) { - bar.update({ status: event.status }); - } - }); - }); - } else { - logger.debug(`Image ${this.image} found locally.`); - } + const envBindings: Array = Object.entries(this.environment).map( + ([key, value]) => `${key}=${value}` + ); - const containers = await this.docker.listContainers({ all: true }); - const existingContainer = containers.find((container: any) => container.Names.find((name: any) => name.startsWith(`/composio-`))); - - if (existingContainer) { - logger.debug(`Container with name ${this.id} is already running.`); - this.container = this.docker.getContainer(existingContainer.Id); - await this.container.restart(); - this.port = existingContainer.Ports.find((port: any) => port.PrivatePort === 8000)?.PublicPort!; - this.url = `http://localhost:${this.port}/api`; - } else { - const { exposedPorts, portBindings, volumeBindings, envBindings } = this.getBaseDockerConfig(); - const containerOptions: Docker.ContainerCreateOptions = { - Image: this.image, - name: this.id, - Cmd: ["/root/entrypoint.sh"], - Tty: true, - AttachStdin: true, - AttachStdout: true, - AttachStderr: true, - OpenStdin: true, - StdinOnce: false, - ExposedPorts: exposedPorts, - HostConfig: { - PortBindings: portBindings, - Binds: volumeBindings, - }, - Env: envBindings, - }; - - this.container = await this.docker.createContainer(containerOptions); - await this.container.start(); - } - await this.waitForContainer(); + if (IS_DEV_MODE === "1") { + envBindings.push(`${ENV_COMPOSIO_DEV_MODE}=1`); } - private async waitForContainer() { - while (true) { - try { - const response = await fetch(this.url, { - method: "GET", - headers: { - "Content-Type": "application/json", - "x-api-key": this.environment.composioAPIKey, - }, - }); - if (response.ok) { - return; - } - } catch (error) { - await new Promise((resolve) => setTimeout(resolve, 100)); + return { exposedPorts, portBindings, volumeBindings, envBindings }; + } + + async setup() { + this.port = await getFreePort(); + this.url = `http://localhost:${this.port}/api`; + + const images = await this.docker.listImages(); + const imageExists = images.some( + (image: any) => + image.RepoTags && + image.RepoTags.find((tag: any) => tag.startsWith(this.image)) + ); + + if (!imageExists) { + logger.debug(`Pulling Docker image ${this.image}...`); + const cliProgress = nodeExternalRequire("cli-progress"); + + const bar: CliProgress.Bar = new cliProgress.SingleBar( + { + format: "{bar} | {percentage}% | {status}", + hideCursor: true, + }, + cliProgress.Presets.shades_classic + ); + + bar.start(100, 0, { status: "Initializing..." }); + bar.update({ + status: `Image ${this.image} not found locally. Pulling from Docker Hub...`, + }); + await new Promise((resolve, reject) => { + this.docker.pull(this.image, (err: any, stream: any) => { + if (err) { + bar.stop(); + logger.error("Failed to pull Docker image."); + return reject(err); + } + this.docker.modem.followProgress(stream, onFinished, onProgress); + + function onFinished(err: any, output: any) { + if (err) { + bar.stop(); + logger.error("Failed to pull Docker image."); + return reject(err); } - } + bar.update(100, { status: "Docker image pulled successfully." }); + bar.stop(); + resolve(output); + } + + function onProgress(event: any) { + bar.update({ status: event.status }); + } + }); + }); + } else { + logger.debug(`Image ${this.image} found locally.`); } - async teardown() { - if (this.container) { - logger.debug(`Stopping container ${this.container.id}...`); - try { - await this.container.kill(); - await this.container.remove(); - } catch (error) { - logger.debug("Failed to stop and remove container:", error); - } + const containers = await this.docker.listContainers({ all: true }); + const existingContainer = containers.find((container: any) => + container.Names.find((name: any) => name.startsWith(`/composio-`)) + ); + + if (existingContainer) { + logger.debug(`Container with name ${this.id} is already running.`); + this.container = this.docker.getContainer(existingContainer.Id); + await this.container.restart(); + this.port = existingContainer.Ports.find( + (port: any) => port.PrivatePort === 8000 + )?.PublicPort!; + this.url = `http://localhost:${this.port}/api`; + } else { + const { exposedPorts, portBindings, volumeBindings, envBindings } = + this.getBaseDockerConfig(); + const containerOptions: Docker.ContainerCreateOptions = { + Image: this.image, + name: this.id, + Cmd: ["/root/entrypoint.sh"], + Tty: true, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + OpenStdin: true, + StdinOnce: false, + ExposedPorts: exposedPorts, + HostConfig: { + PortBindings: portBindings, + Binds: volumeBindings, + }, + Env: envBindings, + }; + + this.container = await this.docker.createContainer(containerOptions); + await this.container.start(); + } + await this.waitForContainer(); + } + + private async waitForContainer() { + while (true) { + try { + const response = await fetch(this.url, { + method: "GET", + headers: { + "Content-Type": "application/json", + "x-api-key": this.environment.composioAPIKey, + }, + }); + if (response.ok) { + return; } + } catch (error) { + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + } + + async teardown() { + if (this.container) { + logger.debug(`Stopping container ${this.container.id}...`); + try { + await this.container.kill(); + await this.container.remove(); + } catch (error) { + logger.debug("Failed to stop and remove container:", error); + } } + } } diff --git a/js/src/env/e2b/workspace.ts b/js/src/env/e2b/workspace.ts index baf23b78ed..7a0e57834c 100644 --- a/js/src/env/e2b/workspace.ts +++ b/js/src/env/e2b/workspace.ts @@ -12,90 +12,94 @@ const TOOLSERVER_URL = "https://{host}/api"; const ENV_E2B_TEMPLATE = "E2B_TEMPLATE"; export interface IE2BConfig extends IWorkspaceConfig { - template?: string; - apiKey?: string; - port?: number; + template?: string; + apiKey?: string; + port?: number; } export class E2BWorkspace extends RemoteWorkspace { - sandbox: Sandbox | undefined; - template: string; - apiKey?: string; - port: number; - - constructor(configRepo: WorkspaceConfig) { - super(configRepo); - this.template = configRepo.config.template || getEnvVariable(ENV_E2B_TEMPLATE, DEFAULT_TEMPLATE)!; - this.apiKey = configRepo.config.apiKey; - this.port = configRepo.config.port || TOOLSERVER_PORT; + sandbox: Sandbox | undefined; + template: string; + apiKey?: string; + port: number; + + constructor(configRepo: WorkspaceConfig) { + super(configRepo); + this.template = + configRepo.config.template || + getEnvVariable(ENV_E2B_TEMPLATE, DEFAULT_TEMPLATE)!; + this.apiKey = configRepo.config.apiKey; + this.port = configRepo.config.port || TOOLSERVER_PORT; + } + + async setup(): Promise { + this.sandbox = await Sandbox.create({ + template: this.template, + envVars: this.environment, + apiKey: this.apiKey, + }); + + this.url = TOOLSERVER_URL.replace( + "{host}", + await this.sandbox!.getHostname(this.port) + ); + + logger.debug("E2B Composio Server is live at " + this.url); + + const process = await this.sandbox!.process.start({ + cmd: "composio apps update", + }); + + await process.wait(); + + const _ssh_username = uuidv4().replace(/-/g, ""); + const _ssh_password = uuidv4().replace(/-/g, ""); + + await this.sandbox!.process.start({ + cmd: `sudo useradd -rm -d /home/${_ssh_username} -s /bin/bash -g root -G sudo ${_ssh_username}`, + }); + + await this.sandbox!.process.start({ + cmd: `echo ${_ssh_username}:${_ssh_password} | sudo chpasswd`, + }); + + await this.sandbox!.process.start({ + cmd: "sudo service ssh restart", + }); + + await this.sandbox!.process.start({ + cmd: `_SSH_USERNAME=${_ssh_username} _SSH_PASSWORD=${_ssh_password} COMPOSIO_LOGGING_LEVEL=debug composio serve -h '0.0.0.0' -p ${this.port}`, + }); + + await this.waitForSpinUp(); + } + + async waitForSpinUp() { + const timeout = 2 * 60 * 1000; // 2 minutes in milliseconds + const startTime = Date.now(); + let status = 0; + + while (status !== 200) { + if (Date.now() - startTime > timeout) { + await this.teardown(); + throw new Error("Timeout: Server did not spin up within 2 minutes"); + } + + try { + status = (await this._request("", "get")).status; + } catch (error) {} + + if (status !== 200) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + } } + } - async setup(): Promise { - this.sandbox = await Sandbox.create({ - template: this.template, - envVars: this.environment, - apiKey: this.apiKey, - }); - - this.url = TOOLSERVER_URL.replace("{host}", await this.sandbox!.getHostname(this.port)); - - logger.debug("E2B Composio Server is live at " + this.url); - - const process = await this.sandbox!.process.start({ - cmd: "composio apps update", - }); - - await process.wait(); - - const _ssh_username = uuidv4().replace(/-/g, ""); - const _ssh_password = uuidv4().replace(/-/g, ""); - - await this.sandbox!.process.start({ - cmd: `sudo useradd -rm -d /home/${_ssh_username} -s /bin/bash -g root -G sudo ${_ssh_username}`, - }); - - await this.sandbox!.process.start({ - cmd: `echo ${_ssh_username}:${_ssh_password} | sudo chpasswd`, - }); - - await this.sandbox!.process.start({ - cmd: "sudo service ssh restart", - }); - - await this.sandbox!.process.start({ - cmd: `_SSH_USERNAME=${_ssh_username} _SSH_PASSWORD=${_ssh_password} COMPOSIO_LOGGING_LEVEL=debug composio serve -h '0.0.0.0' -p ${this.port}`, - }); - - await this.waitForSpinUp(); - } - - async waitForSpinUp() { - const timeout = 2 * 60 * 1000; // 2 minutes in milliseconds - const startTime = Date.now(); - let status = 0; - - while (status !== 200) { - if (Date.now() - startTime > timeout) { - await this.teardown() - throw new Error("Timeout: Server did not spin up within 2 minutes"); - } - - try { - status = (await this._request("", "get")).status; - } catch (error) { - } - - if (status !== 200) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - } - - async teardown(): Promise { - if (!this.sandbox) { - throw new Error("Sandbox not initialized"); - } - await super.teardown(); - await this.sandbox.close(); + async teardown(): Promise { + if (!this.sandbox) { + throw new Error("Sandbox not initialized"); } + await super.teardown(); + await this.sandbox.close(); + } } diff --git a/js/src/env/factory.ts b/js/src/env/factory.ts index e1922da69e..b3f87b2d49 100644 --- a/js/src/env/factory.ts +++ b/js/src/env/factory.ts @@ -1,4 +1,3 @@ - import { E2BWorkspace } from "./e2b/workspace"; import { DockerWorkspace } from "./docker/workspace"; import { Workspace } from "./base"; @@ -6,62 +5,64 @@ import { WorkspaceConfig } from "./config"; import logger from "../utils/logger"; export enum ExecEnv { - HOST = "HOST", - DOCKER = "DOCKER", - E2B = "E2B" + HOST = "HOST", + DOCKER = "DOCKER", + E2B = "E2B", } export class WorkspaceFactory { - workspace: Workspace | null = null; - id: string | null = null; + workspace: Workspace | null = null; + id: string | null = null; - env: ExecEnv; - workspaceConfig: WorkspaceConfig; + env: ExecEnv; + workspaceConfig: WorkspaceConfig; - constructor(env: ExecEnv, kwargs: WorkspaceConfig) { - this.env = env; - this.workspaceConfig = kwargs; - } + constructor(env: ExecEnv, kwargs: WorkspaceConfig) { + this.env = env; + this.workspaceConfig = kwargs; + } - async new() { - if (this.workspace) { - return; - } + async new() { + if (this.workspace) { + return; + } - const sanitizedConfig = { - ...this.workspaceConfig, - host: this.workspaceConfig.config.composioBaseURL, - composioAPIKey: this.workspaceConfig.config.composioAPIKey ? "REDACTED" : "NOT DEFINED" - }; - logger.debug("Creating workspace with config", sanitizedConfig); - - let workspace: Workspace | null = null; - switch (this.workspaceConfig.env) { - case ExecEnv.DOCKER: - workspace = new DockerWorkspace(this.workspaceConfig); - await workspace.setup(); - break; - case ExecEnv.HOST: - break; - case ExecEnv.E2B: - workspace = new E2BWorkspace(this.workspaceConfig); - await workspace.setup(); - break; - default: - throw new Error(`Unknown environment: ${this.workspaceConfig.env}`); - } + const sanitizedConfig = { + ...this.workspaceConfig, + host: this.workspaceConfig.config.composioBaseURL, + composioAPIKey: this.workspaceConfig.config.composioAPIKey + ? "REDACTED" + : "NOT DEFINED", + }; + logger.debug("Creating workspace with config", sanitizedConfig); - if (workspace) { - this.workspace = workspace; - this.id = workspace.id; - } + let workspace: Workspace | null = null; + switch (this.workspaceConfig.env) { + case ExecEnv.DOCKER: + workspace = new DockerWorkspace(this.workspaceConfig); + await workspace.setup(); + break; + case ExecEnv.HOST: + break; + case ExecEnv.E2B: + workspace = new E2BWorkspace(this.workspaceConfig); + await workspace.setup(); + break; + default: + throw new Error(`Unknown environment: ${this.workspaceConfig.env}`); } - async get(id: string | null = null): Promise { - return this.workspace!; + if (workspace) { + this.workspace = workspace; + this.id = workspace.id; } + } - async close(): Promise { - await this.workspace?.teardown(); - } + async get(id: string | null = null): Promise { + return this.workspace!; + } + + async close(): Promise { + await this.workspace?.teardown(); + } } diff --git a/js/src/env/index.ts b/js/src/env/index.ts index fb535011aa..6041c9fea8 100644 --- a/js/src/env/index.ts +++ b/js/src/env/index.ts @@ -4,15 +4,15 @@ import { IE2BConfig } from "./e2b/workspace"; import { IWorkspaceConfig, WorkspaceConfig } from "./config"; export class Workspace { - static Docker(config: IDockerConfig = {}) { - return new WorkspaceConfig(ExecEnv.DOCKER, config as IDockerConfig); - } + static Docker(config: IDockerConfig = {}) { + return new WorkspaceConfig(ExecEnv.DOCKER, config as IDockerConfig); + } - static E2B(config: IE2BConfig = {}) { - return new WorkspaceConfig(ExecEnv.E2B, config as IE2BConfig); - } + static E2B(config: IE2BConfig = {}) { + return new WorkspaceConfig(ExecEnv.E2B, config as IE2BConfig); + } - static Host() { - return new WorkspaceConfig(ExecEnv.HOST, {}); - } -} \ No newline at end of file + static Host() { + return new WorkspaceConfig(ExecEnv.HOST, {}); + } +} diff --git a/js/src/frameworks/cloudflare.spec.ts b/js/src/frameworks/cloudflare.spec.ts index 4e1fb6874e..b64ae0f30c 100644 --- a/js/src/frameworks/cloudflare.spec.ts +++ b/js/src/frameworks/cloudflare.spec.ts @@ -3,39 +3,36 @@ import { CloudflareToolSet } from "./cloudflare"; import { get } from "http"; import { getTestConfig } from "../../config/getTestConfig"; - describe("Apps class tests", () => { - - let cloudflareToolSet: CloudflareToolSet; - beforeAll(() => { - cloudflareToolSet = new CloudflareToolSet({ - apiKey: getTestConfig().COMPOSIO_API_KEY, - baseUrl: getTestConfig().BACKEND_HERMES_URL - }); + let cloudflareToolSet: CloudflareToolSet; + beforeAll(() => { + cloudflareToolSet = new CloudflareToolSet({ + apiKey: getTestConfig().COMPOSIO_API_KEY, + baseUrl: getTestConfig().BACKEND_HERMES_URL, }); + }); - it("check if tools are coming", async () => { - const tools = await cloudflareToolSet.getTools({ - actions: ['GITHUB_GITHUB_API_ROOT'] - }); - - expect(tools.length).toBe(1); + it("check if tools are coming", async () => { + const tools = await cloudflareToolSet.getTools({ + actions: ["GITHUB_GITHUB_API_ROOT"], }); - it("check if apps are coming", async () => { - const tools = await cloudflareToolSet.getTools({ - actions: ['CODEINTERPRETER_GET_FILE_CMD'] - }); + expect(tools.length).toBe(1); + }); - expect(tools.length).toBe(1); + it("check if apps are coming", async () => { + const tools = await cloudflareToolSet.getTools({ + actions: ["CODEINTERPRETER_GET_FILE_CMD"], }); - it("check if send email is coming", async () => { - const tools = await cloudflareToolSet.getTools({ - actions: ['GMAIL_SEND_EMAIL'] - }); + expect(tools.length).toBe(1); + }); - expect(tools.length).toBe(1); + it("check if send email is coming", async () => { + const tools = await cloudflareToolSet.getTools({ + actions: ["GMAIL_SEND_EMAIL"], }); + expect(tools.length).toBe(1); + }); }); diff --git a/js/src/frameworks/cloudflare.ts b/js/src/frameworks/cloudflare.ts index 6bc2246abd..e943be5022 100644 --- a/js/src/frameworks/cloudflare.ts +++ b/js/src/frameworks/cloudflare.ts @@ -24,15 +24,17 @@ export class CloudflareToolSet extends BaseComposioToolSet { /** * Initialize a new CloudflareToolSet instance - * + * * @param config Configuration options including API key, base URL, entity ID and workspace config */ - constructor(config: { - apiKey?: Optional; - baseUrl?: Optional; - entityId?: string; - workspaceConfig?: WorkspaceConfig - }={}) { + constructor( + config: { + apiKey?: Optional; + baseUrl?: Optional; + entityId?: string; + workspaceConfig?: WorkspaceConfig; + } = {} + ) { super( config.apiKey || null, config.baseUrl || COMPOSIO_BASE_URL, @@ -44,7 +46,7 @@ export class CloudflareToolSet extends BaseComposioToolSet { /** * Retrieve available tools based on provided filters - * + * * @param filters Optional filters for actions, apps, tags and use cases * @returns Promise resolving to array of AI text generation tools */ @@ -57,7 +59,8 @@ export class CloudflareToolSet extends BaseComposioToolSet { filterByAvailableApps?: Optional; }): Promise> { const actions = await this.getToolsSchema(filters); - return actions.map((action) => { + return ( + actions.map((action) => { // Format the action schema for Cloudflare Workers AI const formattedSchema: AiTextGenerationToolInput["function"] = { name: action.name!, @@ -78,12 +81,13 @@ export class CloudflareToolSet extends BaseComposioToolSet { function: formattedSchema, }; return tool; - }) || []; + }) || [] + ); } /** * Execute a single tool call - * + * * @param tool The tool to execute with name and arguments * @param entityId Optional entity ID to execute the tool for * @returns Promise resolving to stringified tool execution result @@ -98,15 +102,18 @@ export class CloudflareToolSet extends BaseComposioToolSet { return JSON.stringify( await this.executeAction({ action: tool.name, - params: typeof tool.arguments === "string" ? JSON.parse(tool.arguments) : tool.arguments, - entityId: entityId || this.entityId + params: + typeof tool.arguments === "string" + ? JSON.parse(tool.arguments) + : tool.arguments, + entityId: entityId || this.entityId, }) ); } /** * Handle tool calls from AI text generation output - * + * * @param result The AI text generation output containing tool calls * @param entityId Optional entity ID to execute the tools for * @returns Promise resolving to array of tool execution results @@ -125,5 +132,4 @@ export class CloudflareToolSet extends BaseComposioToolSet { } return outputs; } - } diff --git a/js/src/frameworks/langchain.spec.ts b/js/src/frameworks/langchain.spec.ts index ffb2a62df4..d7da4a25ae 100644 --- a/js/src/frameworks/langchain.spec.ts +++ b/js/src/frameworks/langchain.spec.ts @@ -48,13 +48,12 @@ describe("Apps class tests", () => { callback: async (inputParams, authCredentials, executeRequest) => { try { const res = await executeRequest({ - endpoint: `/user/starred/${inputParams.owner}/${inputParams.repo}`, - method: "PUT", - parameters: [], + endpoint: `/user/starred/${inputParams.owner}/${inputParams.repo}`, + method: "PUT", + parameters: [], }); return res; } catch (e) { - console.error(e); return {}; } }, @@ -67,7 +66,7 @@ describe("Apps class tests", () => { repo: "achievementsof.life", }, entityId: "default", - connectedAccountId: "db3c8d95-73e9-474e-8ae8-edfbdaab98b1" + connectedAccountId: "db3c8d95-73e9-474e-8ae8-edfbdaab98b1", }); expect(actionOuput).toHaveProperty("successfull", true); diff --git a/js/src/frameworks/langchain.ts b/js/src/frameworks/langchain.ts index 26eadc627c..ab979249d5 100644 --- a/js/src/frameworks/langchain.ts +++ b/js/src/frameworks/langchain.ts @@ -7,78 +7,72 @@ import { WorkspaceConfig } from "../env/config"; import { Workspace } from "../env"; export class LangchainToolSet extends BaseComposioToolSet { - /** - * Composio toolset for Langchain framework. - * - */ - static FRAMEWORK_NAME = "langchain"; - static DEFAULT_ENTITY_ID = "default"; + /** + * Composio toolset for Langchain framework. + * + */ + static FRAMEWORK_NAME = "langchain"; + static DEFAULT_ENTITY_ID = "default"; - constructor( - config: { - apiKey?: Optional, - baseUrl?: Optional, - entityId?: string, - workspaceConfig?: WorkspaceConfig - runtime?: string - }={} - ) { - super( - config.apiKey || null, - config.baseUrl || COMPOSIO_BASE_URL, - config?.runtime || LangchainToolSet.FRAMEWORK_NAME, - config.entityId || LangchainToolSet.DEFAULT_ENTITY_ID, - config.workspaceConfig || Workspace.Host() - ); - } + constructor( + config: { + apiKey?: Optional; + baseUrl?: Optional; + entityId?: string; + workspaceConfig?: WorkspaceConfig; + runtime?: string; + } = {} + ) { + super( + config.apiKey || null, + config.baseUrl || COMPOSIO_BASE_URL, + config?.runtime || LangchainToolSet.FRAMEWORK_NAME, + config.entityId || LangchainToolSet.DEFAULT_ENTITY_ID, + config.workspaceConfig || Workspace.Host() + ); + } - private _wrapTool( - schema: Dict, - entityId: Optional = null - ): DynamicStructuredTool { - const action = schema["name"]; - const description = schema["description"]; + private _wrapTool( + schema: Dict, + entityId: Optional = null + ): DynamicStructuredTool { + const action = schema["name"]; + const description = schema["description"]; - const func = async (...kwargs: any[]): Promise => { - return JSON.stringify(await this.executeAction({ - action, - params: kwargs[0], - entityId: entityId || this.entityId - })); - }; + const func = async (...kwargs: any[]): Promise => { + return JSON.stringify( + await this.executeAction({ + action, + params: kwargs[0], + entityId: entityId || this.entityId, + }) + ); + }; - const parameters = jsonSchemaToModel(schema["parameters"]); + const parameters = jsonSchemaToModel(schema["parameters"]); - // @TODO: Add escriiption an other stuff here - - return new DynamicStructuredTool({ - name: action, - description, - schema: parameters, - func: func - }); - } - - - async getTools( - filters: { - actions?: Optional>; - apps?: Sequence; - tags?: Optional>; - useCase?: Optional; - usecaseLimit?: Optional; - filterByAvailableApps?: Optional; - }, - entityId: Optional = null - ): Promise> { - const tools = await this.getToolsSchema(filters, entityId); - return tools.map((tool) => - this._wrapTool( - tool, - entityId || this.entityId - ) - ); - } + // @TODO: Add escriiption an other stuff here + return new DynamicStructuredTool({ + name: action, + description, + schema: parameters, + func: func, + }); + } + async getTools( + filters: { + actions?: Optional>; + apps?: Sequence; + tags?: Optional>; + useCase?: Optional; + usecaseLimit?: Optional; + filterByAvailableApps?: Optional; + }, + entityId: Optional = null + ): Promise> { + const tools = await this.getToolsSchema(filters, entityId); + return tools.map((tool) => this._wrapTool(tool, entityId || this.entityId)); + } } diff --git a/js/src/frameworks/langgraph.spec.ts b/js/src/frameworks/langgraph.spec.ts index ac95a78964..1a4a81a043 100644 --- a/js/src/frameworks/langgraph.spec.ts +++ b/js/src/frameworks/langgraph.spec.ts @@ -3,17 +3,16 @@ import { z } from "zod"; import { getTestConfig } from "../../config/getTestConfig"; import { LangGraphToolSet } from "./langgraph"; - // LangGraph extens langchain class, all the properties are same describe("Apps class tests", () => { - it("getools", async () => { - let langgraphToolSet = new LangGraphToolSet({ - apiKey: getTestConfig().COMPOSIO_API_KEY, - baseUrl: getTestConfig().BACKEND_HERMES_URL, - }); - const tools = await langgraphToolSet.getTools({ - apps: ["github"], - }); - expect(tools).toBeInstanceOf(Array); + it("getools", async () => { + const langgraphToolSet = new LangGraphToolSet({ + apiKey: getTestConfig().COMPOSIO_API_KEY, + baseUrl: getTestConfig().BACKEND_HERMES_URL, + }); + const tools = await langgraphToolSet.getTools({ + apps: ["github"], }); -}) \ No newline at end of file + expect(tools).toBeInstanceOf(Array); + }); +}); diff --git a/js/src/frameworks/openai.spec.ts b/js/src/frameworks/openai.spec.ts index 83be07e33c..fb42f14f97 100644 --- a/js/src/frameworks/openai.spec.ts +++ b/js/src/frameworks/openai.spec.ts @@ -5,50 +5,46 @@ import { getTestConfig } from "../../config/getTestConfig"; import { LangchainToolSet } from "./langchain"; import { OpenAIToolSet } from "./openai"; - describe("Apps class tests", () => { - - let openAIToolset: OpenAIToolSet; - beforeAll(() => { - openAIToolset = new OpenAIToolSet({ - apiKey: getTestConfig().COMPOSIO_API_KEY, - baseUrl: getTestConfig().BACKEND_HERMES_URL - }); + let openAIToolset: OpenAIToolSet; + beforeAll(() => { + openAIToolset = new OpenAIToolSet({ + apiKey: getTestConfig().COMPOSIO_API_KEY, + baseUrl: getTestConfig().BACKEND_HERMES_URL, }); + }); - it("get tools", async () => { - const tools = await openAIToolset.getTools({ - apps: ['github'] - }); - - expect(tools).toBeInstanceOf(Array); - + it("get tools", async () => { + const tools = await openAIToolset.getTools({ + apps: ["github"], }); - it("check if tools are coming", async () => { - const tools = await openAIToolset.getTools({ - actions: ['GITHUB_GITHUB_API_ROOT'] - }); + expect(tools).toBeInstanceOf(Array); + }); - expect(Object.keys(tools).length).toBe(1); + it("check if tools are coming", async () => { + const tools = await openAIToolset.getTools({ + actions: ["GITHUB_GITHUB_API_ROOT"], }); - it("should get tools with usecase limit", async () => { - const tools = await openAIToolset.getTools({ - useCase: "follow user", - apps: ["github"], - useCaseLimit: 1 - }); + expect(Object.keys(tools).length).toBe(1); + }); - expect(tools.length).toBe(1); + it("should get tools with usecase limit", async () => { + const tools = await openAIToolset.getTools({ + useCase: "follow user", + apps: ["github"], + useCaseLimit: 1, }); - it("check if getTools -> actions are coming", async () => { - const tools = await openAIToolset.getTools({ - actions: ['GITHUB_GITHUB_API_ROOT'] - }); + expect(tools.length).toBe(1); + }); - expect(Object.keys(tools).length).toBe(1); + it("check if getTools -> actions are coming", async () => { + const tools = await openAIToolset.getTools({ + actions: ["GITHUB_GITHUB_API_ROOT"], }); + expect(Object.keys(tools).length).toBe(1); + }); }); diff --git a/js/src/frameworks/openai.ts b/js/src/frameworks/openai.ts index 9e818412ad..535a52e0e8 100644 --- a/js/src/frameworks/openai.ts +++ b/js/src/frameworks/openai.ts @@ -12,193 +12,229 @@ type Optional = T | null; type Sequence = Array; export class OpenAIToolSet extends BaseComposioToolSet { - static FRAMEWORK_NAME = "openai"; - static DEFAULT_ENTITY_ID = "default"; - - /** - * Composio toolset for OpenAI framework. - * - * Example: - * ```typescript - * - * ``` - */ - constructor( - config: { - apiKey?: Optional, - baseUrl?: Optional, - entityId?: string, - workspaceConfig?: WorkspaceConfig - }={} - ) { - super( - config.apiKey || null, - config.baseUrl || COMPOSIO_BASE_URL, - OpenAIToolSet.FRAMEWORK_NAME, - config.entityId || OpenAIToolSet.DEFAULT_ENTITY_ID, - config.workspaceConfig || Workspace.Host() + static FRAMEWORK_NAME = "openai"; + static DEFAULT_ENTITY_ID = "default"; + + /** + * Composio toolset for OpenAI framework. + * + * Example: + * ```typescript + * + * ``` + */ + constructor( + config: { + apiKey?: Optional; + baseUrl?: Optional; + entityId?: string; + workspaceConfig?: WorkspaceConfig; + } = {} + ) { + super( + config.apiKey || null, + config.baseUrl || COMPOSIO_BASE_URL, + OpenAIToolSet.FRAMEWORK_NAME, + config.entityId || OpenAIToolSet.DEFAULT_ENTITY_ID, + config.workspaceConfig || Workspace.Host() + ); + } + + async getTools( + filters: { + actions?: Sequence; + apps?: Sequence; + tags?: Optional>; + useCase?: Optional; + useCaseLimit?: Optional; + filterByAvailableApps?: Optional; + }, + entityId?: Optional + ): Promise> { + const mainActions = await this.getToolsSchema(filters, entityId); + return ( + mainActions.map( + (action: NonNullable[0]) => { + const formattedSchema: OpenAI.FunctionDefinition = { + name: action.name!, + description: action.description!, + parameters: action.parameters!, + }; + const tool: OpenAI.ChatCompletionTool = { + type: "function", + function: formattedSchema, + }; + return tool; + } + ) || [] + ); + } + + async executeToolCall( + tool: OpenAI.ChatCompletionMessageToolCall, + entityId: Optional = null + ): Promise { + return JSON.stringify( + await this.executeAction({ + action: tool.function.name, + params: JSON.parse(tool.function.arguments), + entityId: entityId || this.entityId, + }) + ); + } + + async handleToolCall( + chatCompletion: OpenAI.ChatCompletion, + entityId: Optional = null + ): Promise> { + const outputs = []; + for (const message of chatCompletion.choices) { + if (message.message.tool_calls) { + outputs.push( + await this.executeToolCall(message.message.tool_calls[0], entityId) ); + } } + return outputs; + } + + async handleAssistantMessage( + run: OpenAI.Beta.Threads.Run, + entityId: Optional = null + ): Promise< + Array + > { + const tool_calls = + run.required_action?.submit_tool_outputs?.tool_calls || []; + const tool_outputs: Array = + await Promise.all( + tool_calls.map(async (tool_call) => { + logger.debug( + `Executing tool call with ID: ${tool_call.function.name} and parameters: ${JSON.stringify(tool_call.function.arguments)}` + ); + const tool_response = await this.executeToolCall( + tool_call as OpenAI.ChatCompletionMessageToolCall, + entityId || this.entityId + ); + logger.debug( + `Received tool response: ${JSON.stringify(tool_response)}` + ); + return { + tool_call_id: tool_call.id, + output: JSON.stringify(tool_response), + }; + }) + ); + return tool_outputs; + } + + async *waitAndHandleAssistantStreamToolCalls( + client: OpenAI, + runStream: Stream, + thread: OpenAI.Beta.Threads.Thread, + entityId: string | null = null + ): AsyncGenerator { + let runId = null; + + // Start processing the runStream events + for await (const event of runStream) { + yield event; // Yield each event from the stream as it arrives + + if (event.event === "thread.run.created") { + const { id } = event.data; + runId = id; + } + + if (!runId) { + continue; + } + + // Handle the 'requires_action' event + if (event.event === "thread.run.requires_action") { + const toolOutputs = await this.handleAssistantMessage( + event.data, + entityId + ); - async getTools( - filters: { - actions?: Sequence; - apps?: Sequence; - tags?: Optional>; - useCase?: Optional; - useCaseLimit?: Optional; - filterByAvailableApps?: Optional; - }, - entityId?: Optional - ): Promise> { - const mainActions = await this.getToolsSchema(filters, entityId); - return mainActions.map((action: NonNullable[0]) => { - const formattedSchema: OpenAI.FunctionDefinition = { - name: action.name!, - description: action.description!, - parameters: action.parameters!, - }; - const tool: OpenAI.ChatCompletionTool = { - type: "function", - function: formattedSchema - } - return tool; - }) || []; - } - - - async executeToolCall( - tool: OpenAI.ChatCompletionMessageToolCall, - entityId: Optional = null - ): Promise { - return JSON.stringify(await this.executeAction({ - action: tool.function.name, - params: JSON.parse(tool.function.arguments), - entityId: entityId || this.entityId - })); + // Submit the tool outputs + await client.beta.threads.runs.submitToolOutputs(thread.id, runId, { + tool_outputs: toolOutputs, + }); + } + + // Break if the run status becomes inactive + if ( + [ + "thread.run.completed", + "thread.run.failed", + "thread.run.cancelled", + "thread.run.expired", + ].includes(event.event) + ) { + break; + } } - - async handleToolCall( - chatCompletion: OpenAI.ChatCompletion, - entityId: Optional = null - ): Promise> { - const outputs = []; - for (const message of chatCompletion.choices) { - if (message.message.tool_calls) { - outputs.push(await this.executeToolCall(message.message.tool_calls[0], entityId)); - } - } - return outputs; + if (!runId) { + throw new Error("No run ID found"); } + // Handle any final actions after the stream ends + let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId); - async handleAssistantMessage( - run: OpenAI.Beta.Threads.Run, - entityId: Optional = null - ): Promise> { - const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || []; - const tool_outputs: Array = await Promise.all( - tool_calls.map(async (tool_call) => { - logger.debug(`Executing tool call with ID: ${tool_call.function.name} and parameters: ${JSON.stringify(tool_call.function.arguments)}`); - const tool_response = await this.executeToolCall( - tool_call as OpenAI.ChatCompletionMessageToolCall, - entityId || this.entityId - ); - logger.debug(`Received tool response: ${JSON.stringify(tool_response)}`); - return { - tool_call_id: tool_call.id, - output: JSON.stringify(tool_response), - }; - }) + while ( + ["queued", "in_progress", "requires_action"].includes(finalRun.status) + ) { + if (finalRun.status === "requires_action") { + const toolOutputs = await this.handleAssistantMessage( + finalRun, + entityId ); - return tool_outputs; - } - async *waitAndHandleAssistantStreamToolCalls( - client: OpenAI, - runStream: Stream, - thread: OpenAI.Beta.Threads.Thread, - entityId: string | null = null - ): AsyncGenerator { - let runId = null; - - // Start processing the runStream events - for await (const event of runStream) { - yield event; // Yield each event from the stream as it arrives - - if (event.event === 'thread.run.created') { - const { id } = event.data; - runId = id; - } - - if(!runId) { - continue; - } - - // Handle the 'requires_action' event - if (event.event === 'thread.run.requires_action') { - const toolOutputs = await this.handleAssistantMessage(event.data, entityId); - - // Submit the tool outputs - await client.beta.threads.runs.submitToolOutputs(thread.id, runId, { - tool_outputs: toolOutputs - }); - } - - // Break if the run status becomes inactive - if (['thread.run.completed', 'thread.run.failed', 'thread.run.cancelled', 'thread.run.expired'].includes(event.event)) { - break; - } - } - - if(!runId) { - throw new Error("No run ID found"); - } - - // Handle any final actions after the stream ends - let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId); - - while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) { - if (finalRun.status === "requires_action") { - const toolOutputs = await this.handleAssistantMessage(finalRun, entityId); - - // Submit tool outputs - finalRun = await client.beta.threads.runs.submitToolOutputs(thread.id, runId, { - tool_outputs: toolOutputs - }); - } else { - // Update the run status - finalRun = await client.beta.threads.runs.retrieve(thread.id, runId); - await new Promise(resolve => setTimeout(resolve, 500)); // Wait before rechecking - } - } + // Submit tool outputs + finalRun = await client.beta.threads.runs.submitToolOutputs( + thread.id, + runId, + { + tool_outputs: toolOutputs, + } + ); + } else { + // Update the run status + finalRun = await client.beta.threads.runs.retrieve(thread.id, runId); + await new Promise((resolve) => setTimeout(resolve, 500)); // Wait before rechecking + } } - - - async waitAndHandleAssistantToolCalls( - client: OpenAI, - run: OpenAI.Beta.Threads.Run, - thread: OpenAI.Beta.Threads.Thread, - entityId: Optional = null - ): Promise { - while (["queued", "in_progress", "requires_action"].includes(run.status)) { - logger.debug(`Current run status: ${run.status}`); - const tool_outputs = await this.handleAssistantMessage(run, entityId || this.entityId); - if (run.status === "requires_action") { - logger.debug(`Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`); - run = await client.beta.threads.runs.submitToolOutputs( - thread.id, - run.id, - { - tool_outputs: tool_outputs - } - ); - } else { - run = await client.beta.threads.runs.retrieve(thread.id, run.id); - await new Promise(resolve => setTimeout(resolve, 500)); - } - } - return run; + } + + async waitAndHandleAssistantToolCalls( + client: OpenAI, + run: OpenAI.Beta.Threads.Run, + thread: OpenAI.Beta.Threads.Thread, + entityId: Optional = null + ): Promise { + while (["queued", "in_progress", "requires_action"].includes(run.status)) { + logger.debug(`Current run status: ${run.status}`); + const tool_outputs = await this.handleAssistantMessage( + run, + entityId || this.entityId + ); + if (run.status === "requires_action") { + logger.debug( + `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}` + ); + run = await client.beta.threads.runs.submitToolOutputs( + thread.id, + run.id, + { + tool_outputs: tool_outputs, + } + ); + } else { + run = await client.beta.threads.runs.retrieve(thread.id, run.id); + await new Promise((resolve) => setTimeout(resolve, 500)); + } } + return run; + } } diff --git a/js/src/frameworks/vercel.spec.ts b/js/src/frameworks/vercel.spec.ts index 0563865b41..c5c6acc50e 100644 --- a/js/src/frameworks/vercel.spec.ts +++ b/js/src/frameworks/vercel.spec.ts @@ -2,31 +2,27 @@ import { describe, it, expect, beforeAll } from "@jest/globals"; import { getTestConfig } from "../../config/getTestConfig"; import { VercelAIToolSet } from "./vercel"; - describe("Apps class tests", () => { - - let vercelAIToolSet: VercelAIToolSet; - beforeAll(() => { - vercelAIToolSet = new VercelAIToolSet({ - apiKey: getTestConfig().COMPOSIO_API_KEY, - baseUrl: getTestConfig().BACKEND_HERMES_URL - }); + let vercelAIToolSet: VercelAIToolSet; + beforeAll(() => { + vercelAIToolSet = new VercelAIToolSet({ + apiKey: getTestConfig().COMPOSIO_API_KEY, + baseUrl: getTestConfig().BACKEND_HERMES_URL, }); + }); - it("check if tools are coming", async () => { - const tools = await vercelAIToolSet.getTools({ - apps: ['github'] - }); - - expect(Object.keys(tools)).toBeInstanceOf(Array); - + it("check if tools are coming", async () => { + const tools = await vercelAIToolSet.getTools({ + apps: ["github"], }); - it("check if actions are coming", async () => { - const tools = await vercelAIToolSet.getTools({ - actions: ['GITHUB_GITHUB_API_ROOT'] - }); - expect(Object.keys(tools).length).toBe(1); - }); + expect(Object.keys(tools)).toBeInstanceOf(Array); + }); + it("check if actions are coming", async () => { + const tools = await vercelAIToolSet.getTools({ + actions: ["GITHUB_GITHUB_API_ROOT"], + }); + expect(Object.keys(tools).length).toBe(1); + }); }); diff --git a/js/src/frameworks/vercel.ts b/js/src/frameworks/vercel.ts index 61bae081e7..1d2c8b3b29 100644 --- a/js/src/frameworks/vercel.ts +++ b/js/src/frameworks/vercel.ts @@ -6,7 +6,6 @@ import { CEG } from "../sdk/utils/error"; import { SDK_ERROR_CODES } from "../sdk/utils/errors/src/constants"; type Optional = T | null; - const zExecuteToolCallParams = z.object({ actions: z.array(z.string()).optional(), apps: z.array(z.string()).optional(), @@ -18,14 +17,16 @@ const zExecuteToolCallParams = z.object({ tags: z.array(z.string()).optional(), filterByAvailableApps: z.boolean().optional().default(false), -}) +}); export class VercelAIToolSet extends BaseComposioToolSet { - constructor(config: { - apiKey?: Optional; - baseUrl?: Optional; - entityId?: string; - }={}) { + constructor( + config: { + apiKey?: Optional; + baseUrl?: Optional; + entityId?: string; + } = {} + ) { super( config.apiKey || null, config.baseUrl || null, @@ -40,40 +41,46 @@ export class VercelAIToolSet extends BaseComposioToolSet { description: schema.description, parameters, execute: async (params: Record) => { - return await this.executeToolCall({ - name: schema.name, - arguments: JSON.stringify(params) - }, this.entityId); + return await this.executeToolCall( + { + name: schema.name, + arguments: JSON.stringify(params), + }, + this.entityId + ); }, }); } - - // change this implementation async getTools(filters: { - actions?: Array + actions?: Array; apps?: Array; tags?: Optional>; useCase?: Optional; usecaseLimit?: Optional; filterByAvailableApps?: Optional; }): Promise<{ [key: string]: any }> { + const { + apps, + tags, + useCase, + usecaseLimit, + filterByAvailableApps, + actions, + } = zExecuteToolCallParams.parse(filters); - const {apps, tags, useCase, usecaseLimit, filterByAvailableApps, actions} = zExecuteToolCallParams.parse(filters); - const actionsList = await this.client.actions.list({ ...(apps && { apps: apps?.join(",") }), ...(tags && { tags: tags?.join(",") }), ...(useCase && { useCase: useCase }), ...(actions && { actions: actions?.join(",") }), ...(usecaseLimit && { usecaseLimit: usecaseLimit }), - filterByAvailableApps: filterByAvailableApps ?? undefined + filterByAvailableApps: filterByAvailableApps ?? undefined, }); - const tools = {}; - actionsList.items?.forEach(actionSchema => { + actionsList.items?.forEach((actionSchema) => { // @ts-ignore tools[actionSchema.name!] = this.generateVercelTool(actionSchema); }); @@ -81,18 +88,19 @@ export class VercelAIToolSet extends BaseComposioToolSet { return tools; } - async executeToolCall( - tool: { name: string; arguments: unknown; }, + tool: { name: string; arguments: unknown }, entityId: Optional = null ): Promise { return JSON.stringify( await this.executeAction({ action: tool.name, - params: typeof tool.arguments === "string" ? JSON.parse(tool.arguments) : tool.arguments, - entityId: entityId || this.entityId + params: + typeof tool.arguments === "string" + ? JSON.parse(tool.arguments) + : tool.arguments, + entityId: entityId || this.entityId, }) ); } - } diff --git a/js/src/index.ts b/js/src/index.ts index 21f2e2a517..befee8b2ee 100644 --- a/js/src/index.ts +++ b/js/src/index.ts @@ -1,11 +1,21 @@ import { Composio } from "./sdk/index"; import { LangchainToolSet } from "./frameworks/langchain"; -import { OpenAIToolSet } from "./frameworks/openai";; +import { OpenAIToolSet } from "./frameworks/openai"; import { CloudflareToolSet } from "./frameworks/cloudflare"; import { VercelAIToolSet } from "./frameworks/vercel"; import { LangGraphToolSet } from "./frameworks/langgraph"; import { Workspace } from "./env/index"; -const { APPS,ACTIONS } = require("./constants"); +const { APPS, ACTIONS } = require("./constants"); -export { Composio, LangchainToolSet, OpenAIToolSet, CloudflareToolSet, VercelAIToolSet, Workspace ,APPS, ACTIONS, LangGraphToolSet }; +export { + Composio, + LangchainToolSet, + OpenAIToolSet, + CloudflareToolSet, + VercelAIToolSet, + Workspace, + APPS, + ACTIONS, + LangGraphToolSet, +}; diff --git a/js/src/sdk/actionRegistry.ts b/js/src/sdk/actionRegistry.ts index b6790f6370..596d35f1e3 100644 --- a/js/src/sdk/actionRegistry.ts +++ b/js/src/sdk/actionRegistry.ts @@ -1,10 +1,10 @@ import { - z, - ZodType, - ZodObject, - ZodString, - AnyZodObject, - ZodOptional, + z, + ZodType, + ZodObject, + ZodString, + AnyZodObject, + ZodOptional, } from "zod"; import { zodToJsonSchema, JsonSchema7Type } from "zod-to-json-schema"; import { ActionProxyRequestConfigDTO } from "./client"; @@ -14,160 +14,160 @@ import { CEG } from "./utils/error"; type ExecuteRequest = Omit; export interface CreateActionOptions { - actionName?: string; - toolName?: string; - description?: string; - inputParams: ZodObject<{ [key: string]: ZodString | ZodOptional }>; - callback: ( - inputParams: Record, - authCredentials: Record | undefined, - executeRequest: (data: ExecuteRequest) => Promise - ) => Promise>; + actionName?: string; + toolName?: string; + description?: string; + inputParams: ZodObject<{ [key: string]: ZodString | ZodOptional }>; + callback: ( + inputParams: Record, + authCredentials: Record | undefined, + executeRequest: (data: ExecuteRequest) => Promise + ) => Promise>; } interface ParamsSchema { - definitions: { - input: { - properties: Record; - required?: string[]; - }; + definitions: { + input: { + properties: Record; + required?: string[]; }; + }; } interface ExecuteMetadata { - entityId?: string; - connectionId?: string; + entityId?: string; + connectionId?: string; } export class ActionRegistry { - client: Composio; - customActions: Map; + client: Composio; + customActions: Map; - constructor(client: Composio) { - this.client = client; - this.customActions = new Map(); - } + constructor(client: Composio) { + this.client = client; + this.customActions = new Map(); + } - async createAction( - options: CreateActionOptions - ): Promise> { - const { callback } = options; - if (typeof callback !== "function") { - throw new Error("Callback must be a function"); - } - if (!options.actionName) { - throw new Error("You must provide actionName for this action"); - } - if (!options.inputParams) { - options.inputParams = z.object({}); - } - const params = options.inputParams; - const actionName = options.actionName || callback.name || ""; - const paramsSchema: ParamsSchema = (await zodToJsonSchema(params, { - name: "input", - })) as ParamsSchema; - const _params = paramsSchema.definitions.input.properties; - const composioSchema = { - name: actionName, - description: options.description, - parameters: { - title: actionName, - type: "object", - description: options.description, - required: paramsSchema.definitions.input.required || [], - properties: _params, - }, - response: { - type: "object", - title: "Response for " + actionName, - properties: [], - }, - }; - this.customActions.set(options.actionName?.toLocaleLowerCase() || "", { - metadata: options, - schema: composioSchema, - }); - return composioSchema; + async createAction( + options: CreateActionOptions + ): Promise> { + const { callback } = options; + if (typeof callback !== "function") { + throw new Error("Callback must be a function"); } - - async getActions({ - actions, - }: { - actions: Array; - }): Promise> { - const actionsArr: Array = []; - for (const name of actions) { - const lowerCaseName = name.toLowerCase(); - if (this.customActions.has(lowerCaseName)) { - const action = this.customActions.get(lowerCaseName); - actionsArr.push(action!.schema); - } - } - return actionsArr; + if (!options.actionName) { + throw new Error("You must provide actionName for this action"); } - - async getAllActions(): Promise> { - return Array.from(this.customActions.values()).map((action: any) => action); + if (!options.inputParams) { + options.inputParams = z.object({}); } + const params = options.inputParams; + const actionName = options.actionName || callback.name || ""; + const paramsSchema: ParamsSchema = (await zodToJsonSchema(params, { + name: "input", + })) as ParamsSchema; + const _params = paramsSchema.definitions.input.properties; + const composioSchema = { + name: actionName, + description: options.description, + parameters: { + title: actionName, + type: "object", + description: options.description, + required: paramsSchema.definitions.input.required || [], + properties: _params, + }, + response: { + type: "object", + title: "Response for " + actionName, + properties: [], + }, + }; + this.customActions.set(options.actionName?.toLocaleLowerCase() || "", { + metadata: options, + schema: composioSchema, + }); + return composioSchema; + } - async executeAction( - name: string, - inputParams: Record, - metadata: ExecuteMetadata - ): Promise { - const lowerCaseName = name.toLocaleLowerCase(); - if (!this.customActions.has(lowerCaseName)) { - throw new Error(`Action with name ${name} does not exist`); - } - + async getActions({ + actions, + }: { + actions: Array; + }): Promise> { + const actionsArr: Array = []; + for (const name of actions) { + const lowerCaseName = name.toLowerCase(); + if (this.customActions.has(lowerCaseName)) { const action = this.customActions.get(lowerCaseName); - if (!action) { - throw new Error(`Action with name ${name} could not be retrieved`); - } + actionsArr.push(action!.schema); + } + } + return actionsArr; + } - const { callback, toolName } = action.metadata; - let authCredentials = {}; - if (toolName) { - const entity = await this.client.getEntity(metadata.entityId); - const connection = await entity.getConnection({ - app: toolName, - connectedAccountId: metadata.connectionId - }); - if (!connection) { - throw new Error( - `Connection with app name ${toolName} and entityId ${metadata.entityId} not found` - ); - } - authCredentials = { - headers: connection.connectionParams?.headers, - queryParams: connection.connectionParams?.queryParams, - baseUrl: - connection.connectionParams?.baseUrl || - connection.connectionParams?.base_url, - }; - } - if (typeof callback !== "function") { - throw new Error("Callback must be a function"); - } + async getAllActions(): Promise> { + return Array.from(this.customActions.values()).map((action: any) => action); + } - const executeRequest = async (data: ExecuteRequest) => { - try { - const { data: res } = await apiClient.actionsV2.executeActionProxyV2({ - body: { - ...data, - connectedAccountId: metadata?.connectionId - } as ActionProxyRequestConfigDTO, - }); - return res!; - } catch (error) { - throw CEG.handleAllError(error); - } - }; + async executeAction( + name: string, + inputParams: Record, + metadata: ExecuteMetadata + ): Promise { + const lowerCaseName = name.toLocaleLowerCase(); + if (!this.customActions.has(lowerCaseName)) { + throw new Error(`Action with name ${name} does not exist`); + } - return await callback( - inputParams, - authCredentials, - (data: ExecuteRequest) => executeRequest(data) + const action = this.customActions.get(lowerCaseName); + if (!action) { + throw new Error(`Action with name ${name} could not be retrieved`); + } + + const { callback, toolName } = action.metadata; + let authCredentials = {}; + if (toolName) { + const entity = await this.client.getEntity(metadata.entityId); + const connection = await entity.getConnection({ + app: toolName, + connectedAccountId: metadata.connectionId, + }); + if (!connection) { + throw new Error( + `Connection with app name ${toolName} and entityId ${metadata.entityId} not found` ); + } + authCredentials = { + headers: connection.connectionParams?.headers, + queryParams: connection.connectionParams?.queryParams, + baseUrl: + connection.connectionParams?.baseUrl || + connection.connectionParams?.base_url, + }; } + if (typeof callback !== "function") { + throw new Error("Callback must be a function"); + } + + const executeRequest = async (data: ExecuteRequest) => { + try { + const { data: res } = await apiClient.actionsV2.executeActionProxyV2({ + body: { + ...data, + connectedAccountId: metadata?.connectionId, + } as ActionProxyRequestConfigDTO, + }); + return res!; + } catch (error) { + throw CEG.handleAllError(error); + } + }; + + return await callback( + inputParams, + authCredentials, + (data: ExecuteRequest) => executeRequest(data) + ); + } } diff --git a/js/src/sdk/base.toolset.spec.ts b/js/src/sdk/base.toolset.spec.ts index 2137507abd..83d60ae25e 100644 --- a/js/src/sdk/base.toolset.spec.ts +++ b/js/src/sdk/base.toolset.spec.ts @@ -4,156 +4,168 @@ import { getTestConfig } from "../../config/getTestConfig"; import { ActionExecutionResDto, ExecuteActionResDTO } from "./client"; describe("ComposioToolSet class tests", () => { - let toolset: ComposioToolSet; - const testConfig = getTestConfig(); - - beforeAll(() => { - toolset = new ComposioToolSet(testConfig.COMPOSIO_API_KEY, testConfig.BACKEND_HERMES_URL); + let toolset: ComposioToolSet; + const testConfig = getTestConfig(); + + beforeAll(() => { + toolset = new ComposioToolSet( + testConfig.COMPOSIO_API_KEY, + testConfig.BACKEND_HERMES_URL + ); + }); + + it("should create a ComposioToolSet instance", async () => { + const tools = await toolset.getToolsSchema({ apps: ["github"] }); + expect(tools).toBeInstanceOf(Array); + expect(tools).not.toHaveLength(0); + }); + + it("should create a ComposioToolSet instance with apps and tags", async () => { + const tools = await toolset.getToolsSchema({ + apps: ["github"], + tags: ["important"], }); + expect(tools).toBeInstanceOf(Array); + expect(tools).not.toHaveLength(0); + }); - it("should create a ComposioToolSet instance", async() => { - const tools = await toolset.getToolsSchema({ apps: ["github"] }); - expect(tools).toBeInstanceOf(Array); - expect(tools).not.toHaveLength(0); + it("should create a ComposioToolSet instance with actions", async () => { + const tools = await toolset.getActionsSchema({ + actions: ["github_issues_create"], }); - - it("should create a ComposioToolSet instance with apps and tags", async () => { - const tools = await toolset.getToolsSchema({ apps: ["github"], tags: ["important"] }); - expect(tools).toBeInstanceOf(Array); - expect(tools).not.toHaveLength(0); + expect(tools).toBeInstanceOf(Array); + }); + + it("should execute an action", async () => { + const actionName = "github_issues_create"; + const requestBody = { + owner: "utkarsh-dixit", + repo: "speedy", + title: "Test issue", + body: "This is a test issue", + appNames: "github", + }; + + const executionResult = await toolset.executeAction({ + action: actionName, + params: requestBody, + entityId: "default", }); - - it("should create a ComposioToolSet instance with actions", async () => { - const tools = await toolset.getActionsSchema({ actions: ["github_issues_create"] }); - expect(tools).toBeInstanceOf(Array); + expect(executionResult).toBeDefined(); + // @ts-ignore + expect(executionResult).toHaveProperty("successfull", true); + expect(executionResult.data).toBeDefined(); + }); + + it("should execute an action with pre processor", async () => { + const actionName = "github_issues_create"; + const requestBody = { + owner: "utkarsh-dixit", + repo: "speedy", + title: "Test issue", + body: "This is a test issue", + appNames: "github", + }; + + const preProcessor = ({ + action, + toolRequest, + }: { + action: string; + toolRequest: Record; + }) => { + return { + ...toolRequest, + owner: "utkarsh-dixit", + repo: "speedy", + title: "Test issue2", + }; + }; + + const postProcessor = ({ + action, + toolResponse, + }: { + action: string; + toolResponse: ActionExecutionResDto; + }) => { + return { + data: { + ...toolResponse.data, + isPostProcessed: true, + }, + error: toolResponse.error, + successfull: toolResponse.successfull, + }; + }; + + toolset.addPreProcessor(preProcessor); + toolset.addPostProcessor(postProcessor); + + const executionResult = await toolset.executeAction({ + action: actionName, + params: requestBody, + entityId: "default", }); - it("should execute an action", async () => { - - const actionName = "github_issues_create"; - const requestBody = { - owner: "utkarsh-dixit", - repo: "speedy", - title: "Test issue", - body: "This is a test issue", - appNames: "github" - }; - - const executionResult = await toolset.executeAction({ - action: actionName, - params: requestBody, - entityId: "default" - }); - expect(executionResult).toBeDefined(); - // @ts-ignore - expect(executionResult).toHaveProperty('successfull', true); - expect(executionResult.data).toBeDefined(); - - }); + expect(executionResult).toBeDefined(); + // @ts-ignore + expect(executionResult).toHaveProperty("successfull", true); + expect(executionResult.data).toBeDefined(); + expect(executionResult.data.title).toBe("Test issue2"); + expect(executionResult.data.isPostProcessed).toBe(true); + // Remove pre processor and post processor + toolset.removePreProcessor(); - it("should execute an action with pre processor", async () => { - const actionName = "github_issues_create"; - const requestBody = { - owner: "utkarsh-dixit", - repo: "speedy", - title: "Test issue", - body: "This is a test issue", - appNames: "github" - }; - - const preProcessor = ({ action, toolRequest }:{ - action: string, - toolRequest: Record - }) => { - return { - ...toolRequest, - owner: "utkarsh-dixit", - repo: "speedy", - title: "Test issue2", - }; - }; - - const postProcessor = ({ action, toolResponse }:{ - action: string, - toolResponse: ActionExecutionResDto - }) => { - return { - data: { - ...toolResponse.data, - isPostProcessed: true - }, - error: toolResponse.error, - successfull: toolResponse.successfull - }; - }; - - toolset.addPreProcessor(preProcessor); - toolset.addPostProcessor(postProcessor); - - const executionResult = await toolset.executeAction({ - action: actionName, - params: requestBody, - entityId: "default" - }); - - expect(executionResult).toBeDefined(); - // @ts-ignore - expect(executionResult).toHaveProperty('successfull', true); - expect(executionResult.data).toBeDefined(); - expect(executionResult.data.title).toBe("Test issue2"); - expect(executionResult.data.isPostProcessed).toBe(true); - - // Remove pre processor and post processor - toolset.removePreProcessor(); - - const executionResultAfterRemove = await toolset.executeAction({ - action: actionName, - params: requestBody, - entityId: "default" - }); - - expect(executionResultAfterRemove).toBeDefined(); - // @ts-ignore - expect(executionResultAfterRemove).toHaveProperty('successfull', true); - expect(executionResultAfterRemove.data).toBeDefined(); - expect(executionResultAfterRemove.data.title).toBe("Test issue"); + const executionResultAfterRemove = await toolset.executeAction({ + action: actionName, + params: requestBody, + entityId: "default", }); - it("should execute an file upload", async () => { - const ACTION_NAME = "GMAIL_SEND_EMAIL"; - const actions = await toolset.getToolsSchema({ actions: [ACTION_NAME] }); - - // Check if exist - expect(actions[0].parameters.properties["attachment_file_uri_path"]).toBeDefined(); - - const requestBody = { - recipient_email: "himanshu@composio.dev", - subject: "Test email from himanshu", - body: "This is a test email", - attachment_file_uri_path: "https://composio.dev/wp-content/uploads/2024/07/Composio-Logo.webp" - }; - - const executionResult = await toolset.executeAction({ - action: ACTION_NAME, - params: requestBody, - entityId: "default" - }); - expect(executionResult).toBeDefined(); - // @ts-ignore - expect(executionResult).toHaveProperty('successfull', true); - expect(executionResult.data).toBeDefined(); - + expect(executionResultAfterRemove).toBeDefined(); + // @ts-ignore + expect(executionResultAfterRemove).toHaveProperty("successfull", true); + expect(executionResultAfterRemove.data).toBeDefined(); + expect(executionResultAfterRemove.data.title).toBe("Test issue"); + }); + + it("should execute an file upload", async () => { + const ACTION_NAME = "GMAIL_SEND_EMAIL"; + const actions = await toolset.getToolsSchema({ actions: [ACTION_NAME] }); + + // Check if exist + expect( + actions[0].parameters.properties["attachment_file_uri_path"] + ).toBeDefined(); + + const requestBody = { + recipient_email: "himanshu@composio.dev", + subject: "Test email from himanshu", + body: "This is a test email", + attachment_file_uri_path: + "https://composio.dev/wp-content/uploads/2024/07/Composio-Logo.webp", + }; + + const executionResult = await toolset.executeAction({ + action: ACTION_NAME, + params: requestBody, + entityId: "default", }); - - it("should get tools with usecase limit", async () => { - const tools = await toolset.getToolsSchema({ - useCase: "follow user", - apps: ["github"], - useCaseLimit: 1 - }); - - expect(tools.length).toBe(1); + expect(executionResult).toBeDefined(); + // @ts-ignore + expect(executionResult).toHaveProperty("successfull", true); + expect(executionResult.data).toBeDefined(); + }); + + it("should get tools with usecase limit", async () => { + const tools = await toolset.getToolsSchema({ + useCase: "follow user", + apps: ["github"], + useCaseLimit: 1, }); + expect(tools.length).toBe(1); + }); }); diff --git a/js/src/sdk/base.toolset.ts b/js/src/sdk/base.toolset.ts index 7728be400e..32256aeafb 100644 --- a/js/src/sdk/base.toolset.ts +++ b/js/src/sdk/base.toolset.ts @@ -13,7 +13,7 @@ import { ActionRegistry, CreateActionOptions } from "./actionRegistry"; import { getUserDataJson } from "./utils/config"; import { z } from "zod"; type GetListActionsResponse = { - items: any[] + items: any[]; }; const ZExecuteActionParams = z.object({ @@ -22,349 +22,437 @@ const ZExecuteActionParams = z.object({ entityId: z.string(), nlaText: z.string().optional(), connectedAccountId: z.string().optional(), - config: z.object({ - labels: z.array(z.string()).optional(), - }).optional(), + config: z + .object({ + labels: z.array(z.string()).optional(), + }) + .optional(), }); +type TPreProcessor = ({ + action, + toolRequest, +}: { + action: string; + toolRequest: Record; +}) => Record; +type TPostProcessor = ({ + action, + toolResponse, +}: { + action: string; + toolResponse: ActionExecutionResDto; +}) => ActionExecutionResDto; + +const fileProcessor = ({ + action, + toolResponse, +}: { + action: string; + toolResponse: ActionExecutionResDto; +}): ActionExecutionResDto => { + // @ts-expect-error + const isFile = !!toolResponse.data.response_data.file as boolean; + + if (!isFile) { + return toolResponse; + } + + // @ts-expect-error + const fileData = toolResponse.data.response_data.file; + const { name, content } = fileData as { name: string; content: string }; + const file_name_prefix = `${action}_${Date.now()}`; + const filePath = saveFile(file_name_prefix, content); + + // @ts-ignore + delete toolResponse.data.response_data.file; + + return { + error: toolResponse.error, + successfull: toolResponse.successfull, + data: { + ...toolResponse.data, + file_uri_path: filePath, + }, + }; +}; -type TPreProcessor = ({action, toolRequest}: {action: string, toolRequest: Record}) => Record; -type TPostProcessor = ({action, toolResponse}: {action: string, toolResponse: ActionExecutionResDto}) => ActionExecutionResDto; - -const fileProcessor = ({action, toolResponse}:{action: string, toolResponse: ActionExecutionResDto}): ActionExecutionResDto => { - - // @ts-expect-error - const isFile = !!toolResponse.data.response_data.file as boolean; - - if(!isFile) { - return toolResponse; +export class ComposioToolSet { + client: Composio; + apiKey: string; + runtime: string | null; + entityId: string; + workspace: WorkspaceFactory; + workspaceEnv: ExecEnv; + + localActions: IPythonActionDetails["data"] | undefined; + customActionRegistry: ActionRegistry; + + private processors: { + pre?: TPreProcessor; + post?: TPostProcessor; + } = {}; + + constructor( + apiKey: string | null, + baseUrl: string | null = COMPOSIO_BASE_URL, + runtime: string | null = null, + entityId: string = "default", + workspaceConfig: WorkspaceConfig = Workspace.Host() + ) { + const clientApiKey: string | undefined = + apiKey || + getEnvVariable("COMPOSIO_API_KEY") || + (getUserDataJson().api_key as string); + this.apiKey = clientApiKey; + this.client = new Composio( + this.apiKey, + baseUrl || undefined, + runtime as string + ); + this.customActionRegistry = new ActionRegistry(this.client); + this.runtime = runtime; + this.entityId = entityId; + + if (!workspaceConfig.config.composioBaseURL) { + workspaceConfig.config.composioBaseURL = baseUrl; } + if (!workspaceConfig.config.composioAPIKey) { + workspaceConfig.config.composioAPIKey = apiKey; + } + this.workspace = new WorkspaceFactory(workspaceConfig.env, workspaceConfig); + this.workspaceEnv = workspaceConfig.env; - // @ts-expect-error - const fileData = toolResponse.data.response_data.file - const { name, content } = fileData as { name: string, content: string }; - const file_name_prefix = `${action}_${Date.now()}`; - const filePath = saveFile(file_name_prefix, content); - - // @ts-ignore - delete toolResponse.data.response_data.file - - return { - error: toolResponse.error, - successfull: toolResponse.successfull, - data: { - ...toolResponse.data, - file_uri_path: filePath + if (typeof process !== "undefined") { + process.on("exit", async () => { + await this.workspace.workspace?.teardown(); + }); + } + } + + /** + * @deprecated This method is deprecated. Please use this.client.getExpectedParamsForUser instead. + */ + async getExpectedParamsForUser( + params: { + app?: string; + integrationId?: string; + entityId?: string; + authScheme?: + | "OAUTH2" + | "OAUTH1" + | "API_KEY" + | "BASIC" + | "BEARER_TOKEN" + | "BASIC_WITH_JWT"; + } = {} + ) { + return this.client.getExpectedParamsForUser(params); + } + + async setup() { + await this.workspace.new(); + + if (!this.localActions && this.workspaceEnv !== ExecEnv.HOST) { + this.localActions = await ( + this.workspace.workspace as RemoteWorkspace + ).getLocalActionsSchema(); + } + } + + async getActionsSchema( + filters: { actions?: Optional> } = {}, + entityId?: Optional + ): Promise[0]>> { + await this.setup(); + const actions = ( + await this.client.actions.list({ + actions: filters.actions?.join(","), + showAll: true, + }) + ).items; + const localActionsMap = new Map< + string, + NonNullable[0] + >(); + filters.actions?.forEach((action: string) => { + const actionData = this.localActions?.find((a: any) => a.name === action); + if (actionData) { + localActionsMap.set(actionData.name!, actionData); + } + }); + const uniqueLocalActions = Array.from(localActionsMap.values()); + const _newActions = filters.actions?.map((action: string) => + action.toLowerCase() + ); + const toolsWithCustomActions = ( + await this.customActionRegistry.getActions({ actions: _newActions! }) + ).filter((action) => { + if ( + _newActions && + !_newActions.includes(action.parameters.title.toLowerCase()!) + ) { + return false; + } + return true; + }); + + const toolsActions = [ + ...actions!, + ...uniqueLocalActions, + ...toolsWithCustomActions, + ]; + + return toolsActions.map((action) => { + return this.modifyActionForLocalExecution(action); + }); + } + + /** + * @deprecated This method is deprecated. Please use this.client.connectedAccounts.getAuthParams instead. + */ + async getAuthParams(data: { connectedAccountId: string }) { + return this.client.connectedAccounts.getAuthParams({ + connectedAccountId: data.connectedAccountId, + }); + } + + async getTools( + filters: { + apps: Sequence; + tags?: Optional>; + useCase?: Optional; + }, + entityId?: Optional + ): Promise { + throw new Error("Not implemented. Please define in extended toolset"); + } + + async getToolsSchema( + filters: { + actions?: Optional>; + apps?: Array; + tags?: Optional>; + useCase?: Optional; + useCaseLimit?: Optional; + filterByAvailableApps?: Optional; + }, + entityId?: Optional + ): Promise[0]>> { + await this.setup(); + + const apps = await this.client.actions.list({ + ...(filters?.apps && { apps: filters?.apps?.join(",") }), + ...(filters?.tags && { tags: filters?.tags?.join(",") }), + ...(filters?.useCase && { useCase: filters?.useCase }), + ...(filters?.actions && { actions: filters?.actions?.join(",") }), + ...(filters?.useCaseLimit && { usecaseLimit: filters?.useCaseLimit }), + filterByAvailableApps: filters?.filterByAvailableApps ?? undefined, + }); + const localActions = new Map< + string, + NonNullable[0] + >(); + if (filters.apps && Array.isArray(filters.apps)) { + for (const appName of filters.apps!) { + const actionData = this.localActions?.filter( + (a: { appName: string }) => a.appName === appName + ); + if (actionData) { + for (const action of actionData) { + localActions.set(action.name, action); + } } + } } - - -} - -export class ComposioToolSet { - client: Composio; - apiKey: string; - runtime: string | null; - entityId: string; - workspace: WorkspaceFactory; - workspaceEnv: ExecEnv; - - localActions: IPythonActionDetails["data"] | undefined; - customActionRegistry: ActionRegistry; - - private processors: { - pre?: TPreProcessor; - post?: TPostProcessor; - } = {}; - - constructor( - apiKey: string | null, - baseUrl: string | null = COMPOSIO_BASE_URL, - runtime: string | null = null, - entityId: string = "default", - workspaceConfig: WorkspaceConfig = Workspace.Host() - ) { - const clientApiKey: string | undefined = apiKey || getEnvVariable("COMPOSIO_API_KEY") || getUserDataJson().api_key as string; - this.apiKey = clientApiKey; - this.client = new Composio(this.apiKey, baseUrl || undefined, runtime as string); - this.customActionRegistry = new ActionRegistry(this.client); - this.runtime = runtime; - this.entityId = entityId; - - if (!workspaceConfig.config.composioBaseURL) { - workspaceConfig.config.composioBaseURL = baseUrl + const uniqueLocalActions = Array.from(localActions.values()); + + const toolsWithCustomActions = ( + await this.customActionRegistry.getAllActions() + ) + .filter((action) => { + if ( + filters.actions && + !filters.actions.some( + (actionName) => + actionName.toLowerCase() === + action.metadata.actionName!.toLowerCase() + ) + ) { + return false; } - if (!workspaceConfig.config.composioAPIKey) { - workspaceConfig.config.composioAPIKey = apiKey; + if ( + filters.apps && + !filters.apps.some( + (appName) => + appName.toLowerCase() === action.metadata.toolName!.toLowerCase() + ) + ) { + return false; } - this.workspace = new WorkspaceFactory(workspaceConfig.env, workspaceConfig); - this.workspaceEnv = workspaceConfig.env; - - if (typeof process !== 'undefined') { - process.on("exit", async () => { - await this.workspace.workspace?.teardown(); - }); + if ( + filters.tags && + !filters.tags.some( + (tag) => tag.toLocaleLowerCase() === "custom".toLocaleLowerCase() + ) + ) { + return false; } - + return true; + }) + .map((action) => { + return action.schema; + }); + + const toolsActions = [ + ...apps?.items!, + ...uniqueLocalActions, + ...toolsWithCustomActions, + ]; + + return toolsActions.map((action) => { + return this.modifyActionForLocalExecution(action); + }); + } + + modifyActionForLocalExecution(toolSchema: any) { + const properties = convertReqParams(toolSchema.parameters.properties); + toolSchema.parameters.properties = properties; + const response = toolSchema.response.properties; + + for (const responseKey of Object.keys(response)) { + if (responseKey === "file") { + response["file_uri_path"] = { + type: "string", + title: "Name", + description: + "Local absolute path to the file or http url to the file", + }; + + delete response[responseKey]; + } } - /** - * @deprecated This method is deprecated. Please use this.client.getExpectedParamsForUser instead. - */ - async getExpectedParamsForUser( - params: { app?: string; integrationId?: string; entityId?: string; authScheme?: "OAUTH2" | "OAUTH1" | "API_KEY" | "BASIC" | "BEARER_TOKEN" | "BASIC_WITH_JWT" } = {}, - ) { - return this.client.getExpectedParamsForUser(params); + return toolSchema; + } + + async createAction(options: CreateActionOptions) { + return this.customActionRegistry.createAction(options); + } + + private isCustomAction(action: string) { + return this.customActionRegistry + .getActions({ actions: [action] }) + .then((actions) => actions.length > 0); + } + + async executeAction(functionParams: z.infer) { + const { + action, + params: inputParams = {}, + entityId = "default", + nlaText = "", + connectedAccountId, + } = ZExecuteActionParams.parse(functionParams); + let params = inputParams; + + const isPreProcessorAndIsFunction = + typeof this?.processors?.pre === "function"; + if (isPreProcessorAndIsFunction && this.processors.pre) { + params = this.processors.pre({ + action: action, + toolRequest: params, + }); } - - async setup() { - await this.workspace.new(); - - if (!this.localActions && this.workspaceEnv !== ExecEnv.HOST) { - this.localActions = await (this.workspace.workspace as RemoteWorkspace).getLocalActionsSchema(); - } - } - - async getActionsSchema( - filters: { actions?: Optional> } = {}, - entityId?: Optional - ): Promise[0]>> { - await this.setup(); - let actions = (await this.client.actions.list({ - actions: filters.actions?.join(","), - showAll: true - })).items; - const localActionsMap = new Map[0]>(); - filters.actions?.forEach((action: string) => { - const actionData = this.localActions?.find((a: any) => a.name === action); - if (actionData) { - localActionsMap.set(actionData.name!, actionData); - } - }); - const uniqueLocalActions = Array.from(localActionsMap.values()); - const _newActions = filters.actions?.map((action: string) => action.toLowerCase()); - const toolsWithCustomActions = (await this.customActionRegistry.getActions({ actions: _newActions! })).filter((action: any) => { - if (_newActions && !_newActions.includes(action.parameters.title.toLowerCase()!)) { - return false; - } - return true; - }).map((action: any) => { - return action; + // Custom actions are always executed in the host/local environment for JS SDK + if (await this.isCustomAction(action)) { + let accountId = connectedAccountId; + if (!accountId) { + // fetch connected account id + const connectedAccounts = await this.client.connectedAccounts.list({ + user_uuid: entityId, }); + accountId = connectedAccounts?.items[0]?.id; + } - const toolsActions = [...actions!, ...uniqueLocalActions, ...toolsWithCustomActions]; + if (!accountId) { + throw new Error("No connected account found for the user"); + } - return toolsActions.map((action: any) => { - return this.modifyActionForLocalExecution(action); - }); + return this.customActionRegistry.executeAction(action, params, { + entityId: entityId, + connectionId: accountId, + }); } - - /** - * @deprecated This method is deprecated. Please use this.client.connectedAccounts.getAuthParams instead. - */ - async getAuthParams(data: { connectedAccountId: string }) { - return this.client.connectedAccounts.getAuthParams({ - connectedAccountId: data.connectedAccountId - }); + if (this.workspaceEnv && this.workspaceEnv !== ExecEnv.HOST) { + const workspace = await this.workspace.get(); + return workspace.executeAction(action, params, { + entityId: this.entityId, + }); } - - async getTools( - filters: { - apps: Sequence; - tags?: Optional>; - useCase?: Optional; - }, - entityId?: Optional - ): Promise { - throw new Error("Not implemented. Please define in extended toolset"); + const convertedParams = await converReqParamForActionExecution(params); + const data = (await this.client.getEntity(entityId).execute({ + actionName: action, + params: convertedParams, + text: nlaText, + })) as ActionExecutionResDto; + + return this.processResponse(data, { + action: action, + entityId: entityId, + }); + } + + private async processResponse( + data: ActionExecutionResDto, + meta: { + action: string; + entityId: string; } - - async getToolsSchema( - filters: { - actions?: Optional>; - apps?: Array; - tags?: Optional>; - useCase?: Optional; - useCaseLimit?: Optional; - filterByAvailableApps?: Optional; - }, - entityId?: Optional - ): Promise[0]>> { - await this.setup(); - - const apps = await this.client.actions.list({ - ...(filters?.apps && { apps: filters?.apps?.join(",") }), - ...(filters?.tags && { tags: filters?.tags?.join(",") }), - ...(filters?.useCase && { useCase: filters?.useCase }), - ...(filters?.actions && { actions: filters?.actions?.join(",") }), - ...(filters?.useCaseLimit && { usecaseLimit: filters?.useCaseLimit }), - filterByAvailableApps: filters?.filterByAvailableApps ?? undefined - }); - const localActions = new Map[0]>(); - if (filters.apps && Array.isArray(filters.apps)) { - for (const appName of filters.apps!) { - const actionData = this.localActions?.filter((a: any) => a.appName === appName); - if (actionData) { - for (const action of actionData) { - localActions.set(action.name, action); - } - } - } - } - const uniqueLocalActions = Array.from(localActions.values()); - - const toolsWithCustomActions = (await this.customActionRegistry.getAllActions()).filter((action: any) => { - if (filters.actions && !filters.actions.some(actionName => actionName.toLowerCase() === action.metadata.actionName!.toLowerCase())) { - return false; - } - if (filters.apps && !filters.apps.some(appName => appName.toLowerCase() === action.metadata.toolName!.toLowerCase())) { - return false; - } - if (filters.tags && !filters.tags.some(tag => tag.toLocaleLowerCase() === "custom".toLocaleLowerCase())) { - return false; - } - return true; - }).map((action: any) => { - return action.schema; - }); - - const toolsActions = [...apps?.items!, ...uniqueLocalActions, ...toolsWithCustomActions]; - - return toolsActions.map((action: any) => { - return this.modifyActionForLocalExecution(action); - }); - - } - - modifyActionForLocalExecution(toolSchema: any) { - const properties = convertReqParams(toolSchema.parameters.properties); - toolSchema.parameters.properties = properties; - const response = toolSchema.response.properties; - - for (const responseKey of Object.keys(response)) { - if (responseKey === "file") { - response["file_uri_path"] = { - type: "string", - title: "Name", - description: "Local absolute path to the file or http url to the file" - } - - delete response[responseKey]; - } - } - - return toolSchema; - } - - async createAction(options: CreateActionOptions) { - return this.customActionRegistry.createAction(options); - } - - private isCustomAction(action: string) { - return this.customActionRegistry.getActions({ actions: [action] }).then((actions: any) => actions.length > 0); - } - - async executeAction(functionParams: z.infer) { - - const {action, params:inputParams={}, entityId="default", nlaText="", connectedAccountId} = ZExecuteActionParams.parse(functionParams); - let params = inputParams; - - const isPreProcessorAndIsFunction = typeof this?.processors?.pre === "function"; - if(isPreProcessorAndIsFunction && this.processors.pre) { - params = this.processors.pre({ - action: action, - toolRequest: params - }); - } - // Custom actions are always executed in the host/local environment for JS SDK - if (await this.isCustomAction(action)) { - let accountId = connectedAccountId; - if (!accountId) { - // fetch connected account id - const connectedAccounts = await this.client.connectedAccounts.list({ - user_uuid: entityId - }); - accountId = connectedAccounts?.items[0]?.id; - } - - if(!accountId) { - throw new Error("No connected account found for the user"); - } - - return this.customActionRegistry.executeAction(action, params, { - entityId: entityId, - connectionId: accountId - }); - } - if (this.workspaceEnv && this.workspaceEnv !== ExecEnv.HOST) { - const workspace = await this.workspace.get(); - return workspace.executeAction(action, params, { - entityId: this.entityId - }); - } - const convertedParams = await converReqParamForActionExecution(params); - const data = await this.client.getEntity(entityId).execute({actionName: action, params: convertedParams, text: nlaText}) as ActionExecutionResDto; - - - return this.processResponse(data, { - action: action, - entityId: entityId - }); + ): Promise { + let dataToReturn = { ...data }; + // @ts-ignore + const isFile = !!data?.response_data?.file; + if (isFile) { + dataToReturn = fileProcessor({ + action: meta.action, + toolResponse: dataToReturn, + }) as ActionExecutionResDto; } - private async processResponse( - data: ActionExecutionResDto, - meta: { - action: string, - entityId: string - } - ): Promise { - let dataToReturn = {...data}; - // @ts-ignore - const isFile = !!data?.response_data?.file; - if (isFile) { - dataToReturn = fileProcessor({ - action: meta.action, - toolResponse: dataToReturn - }) as ActionExecutionResDto; - } - - const isPostProcessorAndIsFunction = !!this.processors.post && typeof this.processors.post === "function"; - if (isPostProcessorAndIsFunction && this.processors.post) { - dataToReturn = this.processors.post({ - action: meta.action, - toolResponse: dataToReturn - }); - } - - return dataToReturn; + const isPostProcessorAndIsFunction = + !!this.processors.post && typeof this.processors.post === "function"; + if (isPostProcessorAndIsFunction && this.processors.post) { + dataToReturn = this.processors.post({ + action: meta.action, + toolResponse: dataToReturn, + }); } + return dataToReturn; + } - async addPreProcessor(processor: TPreProcessor) { - if(typeof processor === "function") { - this.processors.pre = processor as TPreProcessor; - } - else { - throw new Error("Invalid processor type"); - } - } - - async addPostProcessor(processor: TPostProcessor) { - if(typeof processor === "function") { - this.processors.post = processor as TPostProcessor; - } - else { - throw new Error("Invalid processor type"); - } + async addPreProcessor(processor: TPreProcessor) { + if (typeof processor === "function") { + this.processors.pre = processor as TPreProcessor; + } else { + throw new Error("Invalid processor type"); } + } - async removePreProcessor() { - delete this.processors.pre; + async addPostProcessor(processor: TPostProcessor) { + if (typeof processor === "function") { + this.processors.post = processor as TPostProcessor; + } else { + throw new Error("Invalid processor type"); } + } - async removePostProcessor() { - delete this.processors.post; - } + async removePreProcessor() { + delete this.processors.pre; + } -} \ No newline at end of file + async removePostProcessor() { + delete this.processors.post; + } +} diff --git a/js/src/sdk/client/client.ts b/js/src/sdk/client/client.ts index b32b0a7ec6..57a69f61a0 100644 --- a/js/src/sdk/client/client.ts +++ b/js/src/sdk/client/client.ts @@ -1,14 +1,14 @@ import * as SDKClient from "./services.gen"; export default { - logs: SDKClient.LogsService, - actionsV1: SDKClient.ActionsService, - actionsV2: SDKClient.ActionsService, - apiKeys: SDKClient.ApiKeysService, - clientAuth: SDKClient.AuthService, - cli: SDKClient.CliService, - appConnector: SDKClient.IntegrationsService, - apps: SDKClient.AppsService, - connections: SDKClient.ConnectionsService, - triggers: SDKClient.TriggersService, + logs: SDKClient.LogsService, + actionsV1: SDKClient.ActionsService, + actionsV2: SDKClient.ActionsService, + apiKeys: SDKClient.ApiKeysService, + clientAuth: SDKClient.AuthService, + cli: SDKClient.CliService, + appConnector: SDKClient.IntegrationsService, + apps: SDKClient.AppsService, + connections: SDKClient.ConnectionsService, + triggers: SDKClient.TriggersService, }; diff --git a/js/src/sdk/client/core/ApiError.ts b/js/src/sdk/client/core/ApiError.ts index 36675d288a..47ac0058c3 100644 --- a/js/src/sdk/client/core/ApiError.ts +++ b/js/src/sdk/client/core/ApiError.ts @@ -1,21 +1,25 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; +import type { ApiRequestOptions } from "./ApiRequestOptions"; +import type { ApiResult } from "./ApiResult"; export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: unknown; - public readonly request: ApiRequestOptions; + public readonly url: string; + public readonly status: number; + public readonly statusText: string; + public readonly body: unknown; + public readonly request: ApiRequestOptions; - constructor(request: ApiRequestOptions, response: ApiResult, message: string) { - super(message); + constructor( + request: ApiRequestOptions, + response: ApiResult, + message: string + ) { + super(message); - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - this.request = request; - } -} \ No newline at end of file + this.name = "ApiError"; + this.url = response.url; + this.status = response.status; + this.statusText = response.statusText; + this.body = response.body; + this.request = request; + } +} diff --git a/js/src/sdk/client/core/ApiRequestOptions.ts b/js/src/sdk/client/core/ApiRequestOptions.ts index f25a8910f3..96560d809b 100644 --- a/js/src/sdk/client/core/ApiRequestOptions.ts +++ b/js/src/sdk/client/core/ApiRequestOptions.ts @@ -1,13 +1,20 @@ export type ApiRequestOptions = { - readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; - readonly url: string; - readonly path?: Record; - readonly cookies?: Record; - readonly headers?: Record; - readonly query?: Record; - readonly formData?: Record; - readonly body?: any; - readonly mediaType?: string; - readonly responseHeader?: string; - readonly errors?: Record; -}; \ No newline at end of file + readonly method: + | "GET" + | "PUT" + | "POST" + | "DELETE" + | "OPTIONS" + | "HEAD" + | "PATCH"; + readonly url: string; + readonly path?: Record; + readonly cookies?: Record; + readonly headers?: Record; + readonly query?: Record; + readonly formData?: Record; + readonly body?: any; + readonly mediaType?: string; + readonly responseHeader?: string; + readonly errors?: Record; +}; diff --git a/js/src/sdk/client/core/ApiResult.ts b/js/src/sdk/client/core/ApiResult.ts index 4c58e39138..05040ba816 100644 --- a/js/src/sdk/client/core/ApiResult.ts +++ b/js/src/sdk/client/core/ApiResult.ts @@ -1,7 +1,7 @@ export type ApiResult = { - readonly body: TData; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly url: string; -}; \ No newline at end of file + readonly body: TData; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly url: string; +}; diff --git a/js/src/sdk/client/core/CancelablePromise.ts b/js/src/sdk/client/core/CancelablePromise.ts index 1431a8a99f..31b58ba5ba 100644 --- a/js/src/sdk/client/core/CancelablePromise.ts +++ b/js/src/sdk/client/core/CancelablePromise.ts @@ -1,128 +1,128 @@ import logger from "../../../utils/logger"; export class CancelError extends Error { - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } + constructor(message: string) { + super(message); + this.name = "CancelError"; + } + + public get isCancelled(): boolean { + return true; + } } export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; + readonly isResolved: boolean; + readonly isRejected: boolean; + readonly isCancelled: boolean; - (cancelHandler: () => void): void; + (cancelHandler: () => void): void; } export class CancelablePromise implements Promise { - private _isResolved: boolean; - private _isRejected: boolean; - private _isCancelled: boolean; - readonly cancelHandlers: (() => void)[]; - readonly promise: Promise; - private _resolve?: (value: T | PromiseLike) => void; - private _reject?: (reason?: unknown) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: unknown) => void, - onCancel: OnCancel - ) => void - ) { - this._isResolved = false; - this._isRejected = false; - this._isCancelled = false; - this.cancelHandlers = []; - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isResolved = true; - if (this._resolve) this._resolve(value); - }; - - const onReject = (reason?: unknown): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isRejected = true; - if (this._reject) this._reject(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this.cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this._isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this._isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this._isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - get [Symbol.toStringTag]() { - return "Cancellable Promise"; - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null - ): Promise { - return this.promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: unknown) => TResult | PromiseLike) | null - ): Promise { - return this.promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.promise.finally(onFinally); - } - - public cancel(): void { - if (this._isResolved || this._isRejected || this._isCancelled) { - return; - } - this._isCancelled = true; - if (this.cancelHandlers.length) { - try { - for (const cancelHandler of this.cancelHandlers) { - cancelHandler(); - } - } catch (error) { - logger.warn('Cancellation threw an error', error); - return; - } - } - this.cancelHandlers.length = 0; - if (this._reject) this._reject(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this._isCancelled; - } -} \ No newline at end of file + private _isResolved: boolean; + private _isRejected: boolean; + private _isCancelled: boolean; + readonly cancelHandlers: (() => void)[]; + readonly promise: Promise; + private _resolve?: (value: T | PromiseLike) => void; + private _reject?: (reason?: unknown) => void; + + constructor( + executor: ( + resolve: (value: T | PromiseLike) => void, + reject: (reason?: unknown) => void, + onCancel: OnCancel + ) => void + ) { + this._isResolved = false; + this._isRejected = false; + this._isCancelled = false; + this.cancelHandlers = []; + this.promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + + const onResolve = (value: T | PromiseLike): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isResolved = true; + if (this._resolve) this._resolve(value); + }; + + const onReject = (reason?: unknown): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isRejected = true; + if (this._reject) this._reject(reason); + }; + + const onCancel = (cancelHandler: () => void): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this.cancelHandlers.push(cancelHandler); + }; + + Object.defineProperty(onCancel, "isResolved", { + get: (): boolean => this._isResolved, + }); + + Object.defineProperty(onCancel, "isRejected", { + get: (): boolean => this._isRejected, + }); + + Object.defineProperty(onCancel, "isCancelled", { + get: (): boolean => this._isCancelled, + }); + + return executor(onResolve, onReject, onCancel as OnCancel); + }); + } + + get [Symbol.toStringTag]() { + return "Cancellable Promise"; + } + + public then( + onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null + ): Promise { + return this.promise.then(onFulfilled, onRejected); + } + + public catch( + onRejected?: ((reason: unknown) => TResult | PromiseLike) | null + ): Promise { + return this.promise.catch(onRejected); + } + + public finally(onFinally?: (() => void) | null): Promise { + return this.promise.finally(onFinally); + } + + public cancel(): void { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isCancelled = true; + if (this.cancelHandlers.length) { + try { + for (const cancelHandler of this.cancelHandlers) { + cancelHandler(); + } + } catch (error) { + logger.warn("Cancellation threw an error", error); + return; + } + } + this.cancelHandlers.length = 0; + if (this._reject) this._reject(new CancelError("Request aborted")); + } + + public get isCancelled(): boolean { + return this._isCancelled; + } +} diff --git a/js/src/sdk/client/core/OpenAPI.ts b/js/src/sdk/client/core/OpenAPI.ts index 84390398eb..3687c05fcd 100644 --- a/js/src/sdk/client/core/OpenAPI.ts +++ b/js/src/sdk/client/core/OpenAPI.ts @@ -1,4 +1,4 @@ -import type { ApiRequestOptions } from './ApiRequestOptions'; +import type { ApiRequestOptions } from "./ApiRequestOptions"; type Headers = Record; type Middleware = (value: T) => T | Promise; @@ -24,35 +24,35 @@ export class Interceptors { } export type OpenAPIConfig = { - BASE: string; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - ENCODE_PATH?: ((path: string) => string) | undefined; - HEADERS?: Headers | Resolver | undefined; - PASSWORD?: string | Resolver | undefined; - TOKEN?: string | Resolver | undefined; - USERNAME?: string | Resolver | undefined; - VERSION: string; - WITH_CREDENTIALS: boolean; - interceptors: { - request: Interceptors; - response: Interceptors; - }; + BASE: string; + CREDENTIALS: "include" | "omit" | "same-origin"; + ENCODE_PATH?: ((path: string) => string) | undefined; + HEADERS?: Headers | Resolver | undefined; + PASSWORD?: string | Resolver | undefined; + TOKEN?: string | Resolver | undefined; + USERNAME?: string | Resolver | undefined; + VERSION: string; + WITH_CREDENTIALS: boolean; + interceptors: { + request: Interceptors; + response: Interceptors; + }; }; export const COMPOSIO_BASE_URL = "https://backend.composio.dev/"; export const OpenAPI: OpenAPIConfig = { - BASE: COMPOSIO_BASE_URL, - CREDENTIALS: 'include', - ENCODE_PATH: undefined, - HEADERS: undefined, - PASSWORD: undefined, - TOKEN: undefined, - USERNAME: undefined, - VERSION: '1.0.0', - WITH_CREDENTIALS: false, - interceptors: { - request: new Interceptors(), - response: new Interceptors(), - }, + BASE: COMPOSIO_BASE_URL, + CREDENTIALS: "include", + ENCODE_PATH: undefined, + HEADERS: undefined, + PASSWORD: undefined, + TOKEN: undefined, + USERNAME: undefined, + VERSION: "1.0.0", + WITH_CREDENTIALS: false, + interceptors: { + request: new Interceptors(), + response: new Interceptors(), + }, }; diff --git a/js/src/sdk/client/core/request.ts b/js/src/sdk/client/core/request.ts index b026435e13..d9074e070b 100644 --- a/js/src/sdk/client/core/request.ts +++ b/js/src/sdk/client/core/request.ts @@ -1,301 +1,337 @@ -import logger from '../../../utils/logger'; -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; +import logger from "../../../utils/logger"; +import { ApiError } from "./ApiError"; +import type { ApiRequestOptions } from "./ApiRequestOptions"; +import type { ApiResult } from "./ApiResult"; +import { CancelablePromise } from "./CancelablePromise"; +import type { OnCancel } from "./CancelablePromise"; +import type { OpenAPIConfig } from "./OpenAPI"; export const isString = (value: unknown): value is string => { - return typeof value === 'string'; + return typeof value === "string"; }; export const isStringWithValue = (value: unknown): value is string => { - return isString(value) && value !== ''; + return isString(value) && value !== ""; }; export const isBlob = (value: any): value is Blob => { - return value instanceof Blob; + return value instanceof Blob; }; export const isFormData = (value: unknown): value is FormData => { - return value instanceof FormData; + return value instanceof FormData; }; export const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } + try { + return btoa(str); + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString("base64"); + } }; export const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: unknown) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const encodePair = (key: string, value: unknown) => { - if (value === undefined || value === null) { - return; - } - - if (value instanceof Date) { - append(key, value.toISOString()); - } else if (Array.isArray(value)) { - value.forEach(v => encodePair(key, v)); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); - } else { - append(key, value); - } - }; - - Object.entries(params).forEach(([key, value]) => encodePair(key, value)); - - return qs.length ? `?${qs.join('&')}` : ''; + const qs: string[] = []; + + const append = (key: string, value: unknown) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); + }; + + const encodePair = (key: string, value: unknown) => { + if (value === undefined || value === null) { + return; + } + + if (value instanceof Date) { + append(key, value.toISOString()); + } else if (Array.isArray(value)) { + value.forEach((v) => encodePair(key, v)); + } else if (typeof value === "object") { + Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); + } else { + append(key, value); + } + }; + + Object.entries(params).forEach(([key, value]) => encodePair(key, value)); + + return qs.length ? `?${qs.join("&")}` : ""; }; const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = config.BASE + path; - return options.query ? url + getQueryString(options.query) : url; + const encoder = config.ENCODE_PATH || encodeURI; + + const path = options.url + .replace("{api-version}", config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + return encoder(String(options.path[group])); + } + return substring; + }); + + const url = config.BASE + path; + return options.query ? url + getQueryString(options.query) : url; }; -export const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: unknown) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([, value]) => value !== undefined && value !== null) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return undefined; +export const getFormData = ( + options: ApiRequestOptions +): FormData | undefined => { + if (options.formData) { + const formData = new FormData(); + + const process = (key: string, value: unknown) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value); + } else { + formData.append(key, JSON.stringify(value)); + } + }; + + Object.entries(options.formData) + .filter(([, value]) => value !== undefined && value !== null) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => process(key, v)); + } else { + process(key, value); + } + }); + + return formData; + } + return undefined; }; type Resolver = (options: ApiRequestOptions) => Promise; -export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; +export const resolve = async ( + options: ApiRequestOptions, + resolver?: T | Resolver +): Promise => { + if (typeof resolver === "function") { + return (resolver as Resolver)(options); + } + return resolver; }; -export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const [token, username, password, additionalHeaders] = await Promise.all([ - resolve(options, config.TOKEN), - resolve(options, config.USERNAME), - resolve(options, config.PASSWORD), - resolve(options, config.HEADERS), - ]); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([, value]) => value !== undefined && value !== null) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body !== undefined) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); +export const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions +): Promise => { + const [token, username, password, additionalHeaders] = await Promise.all([ + resolve(options, config.TOKEN), + resolve(options, config.USERNAME), + resolve(options, config.PASSWORD), + resolve(options, config.HEADERS), + ]); + + const headers = Object.entries({ + Accept: "application/json", + ...additionalHeaders, + ...options.headers, + }) + .filter(([, value]) => value !== undefined && value !== null) + .reduce( + (headers, [key, value]) => ({ + ...headers, + [key]: String(value), + }), + {} as Record + ); + + if (isStringWithValue(token)) { + headers["Authorization"] = `Bearer ${token}`; + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`); + headers["Authorization"] = `Basic ${credentials}`; + } + + if (options.body !== undefined) { + if (options.mediaType) { + headers["Content-Type"] = options.mediaType; + } else if (isBlob(options.body)) { + headers["Content-Type"] = options.body.type || "application/octet-stream"; + } else if (isString(options.body)) { + headers["Content-Type"] = "text/plain"; + } else if (!isFormData(options.body)) { + headers["Content-Type"] = "application/json"; + } + } + + return new Headers(headers); }; export const getRequestBody = (options: ApiRequestOptions): unknown => { - if (options.body !== undefined) { - if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) { - return JSON.stringify(options.body); - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return undefined; + if (options.body !== undefined) { + if ( + options.mediaType?.includes("application/json") || + options.mediaType?.includes("+json") + ) { + return JSON.stringify(options.body); + } else if ( + isString(options.body) || + isBlob(options.body) || + isFormData(options.body) + ) { + return options.body; + } else { + return JSON.stringify(options.body); + } + } + return undefined; }; export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel + config: OpenAPIConfig, + options: ApiRequestOptions, + url: string, + body: any, + formData: FormData | undefined, + headers: Headers, + onCancel: OnCancel ): Promise => { - const controller = new AbortController(); + const controller = new AbortController(); - let request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; + let request: RequestInit = { + headers, + body: body ?? formData, + method: options.method, + signal: controller.signal, + }; - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } + if (config.WITH_CREDENTIALS) { + request.credentials = config.CREDENTIALS; + } - for (const fn of config.interceptors.request._fns) { - request = await fn(request); - } + for (const fn of config.interceptors.request._fns) { + request = await fn(request); + } - onCancel(() => controller.abort()); + onCancel(() => controller.abort()); - return await fetch(url, request); + return await fetch(url, request); }; -export const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return undefined; +export const getResponseHeader = ( + response: Response, + responseHeader?: string +): string | undefined => { + if (responseHeader) { + const content = response.headers.get(responseHeader); + if (isString(content)) { + return content; + } + } + return undefined; }; export const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const binaryTypes = ['application/octet-stream', 'application/pdf', 'application/zip', 'audio/', 'image/', 'video/']; - if (contentType.includes('application/json') || contentType.includes('+json')) { - return await response.json(); - } else if (binaryTypes.some(type => contentType.includes(type))) { - return await response.blob(); - } else if (contentType.includes('multipart/form-data')) { - return await response.formData(); - } else if (contentType.includes('text/')) { - return await response.text(); - } - } - } catch (error) { - logger.error(`Error in getResponseBody: ${error}`, error); - } - } - return undefined; + if (response.status !== 204) { + try { + const contentType = response.headers.get("Content-Type"); + if (contentType) { + const binaryTypes = [ + "application/octet-stream", + "application/pdf", + "application/zip", + "audio/", + "image/", + "video/", + ]; + if ( + contentType.includes("application/json") || + contentType.includes("+json") + ) { + return await response.json(); + } else if (binaryTypes.some((type) => contentType.includes(type))) { + return await response.blob(); + } else if (contentType.includes("multipart/form-data")) { + return await response.formData(); + } else if (contentType.includes("text/")) { + return await response.text(); + } + } + } catch (error) { + logger.error(`Error in getResponseBody: ${error}`, error); + } + } + return undefined; }; -export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 409: 'Conflict', - 410: 'Gone', - 411: 'Length Required', - 412: 'Precondition Failed', - 413: 'Payload Too Large', - 414: 'URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Range Not Satisfiable', - 417: 'Expectation Failed', - 418: 'Im a teapot', - 421: 'Misdirected Request', - 422: 'Unprocessable Content', - 423: 'Locked', - 424: 'Failed Dependency', - 425: 'Too Early', - 426: 'Upgrade Required', - 428: 'Precondition Required', - 429: 'Too Many Requests', - 431: 'Request Header Fields Too Large', - 451: 'Unavailable For Legal Reasons', - 500: 'Internal Server Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Gateway Timeout', - 505: 'HTTP Version Not Supported', - 506: 'Variant Also Negotiates', - 507: 'Insufficient Storage', - 508: 'Loop Detected', - 510: 'Not Extended', - 511: 'Network Authentication Required', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(options, result, error); - } - - if (!result.ok) { - const errorStatus = result.status ?? 'unknown'; - const errorStatusText = result.statusText ?? 'unknown'; - const errorBody = (() => { - try { - return JSON.stringify(result.body, null, 2); - } catch (e) { - return undefined; - } - })(); - - throw new ApiError(options, result, - `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` - ); - } +export const catchErrorCodes = ( + options: ApiRequestOptions, + result: ApiResult +): void => { + const errors: Record = { + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Payload Too Large", + 414: "URI Too Long", + 415: "Unsupported Media Type", + 416: "Range Not Satisfiable", + 417: "Expectation Failed", + 418: "Im a teapot", + 421: "Misdirected Request", + 422: "Unprocessable Content", + 423: "Locked", + 424: "Failed Dependency", + 425: "Too Early", + 426: "Upgrade Required", + 428: "Precondition Required", + 429: "Too Many Requests", + 431: "Request Header Fields Too Large", + 451: "Unavailable For Legal Reasons", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates", + 507: "Insufficient Storage", + 508: "Loop Detected", + 510: "Not Extended", + 511: "Network Authentication Required", + ...options.errors, + }; + + const error = errors[result.status]; + if (error) { + throw new ApiError(options, result, error); + } + + if (!result.ok) { + const errorStatus = result.status ?? "unknown"; + const errorStatusText = result.statusText ?? "unknown"; + const errorBody = (() => { + try { + return JSON.stringify(result.body, null, 2); + } catch (e) { + return undefined; + } + })(); + + throw new ApiError( + options, + result, + `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` + ); + } }; /** @@ -305,38 +341,52 @@ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): * @returns CancelablePromise * @throws ApiError */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - let response = await sendRequest(config, options, url, body, formData, headers, onCancel); - - for (const fn of config.interceptors.response._fns) { - response = await fn(response); - } - - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; \ No newline at end of file +export const request = ( + config: OpenAPIConfig, + options: ApiRequestOptions +): CancelablePromise => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options); + const formData = getFormData(options); + const body = getRequestBody(options); + const headers = await getHeaders(config, options); + + if (!onCancel.isCancelled) { + let response = await sendRequest( + config, + options, + url, + body, + formData, + headers, + onCancel + ); + + for (const fn of config.interceptors.response._fns) { + response = await fn(response); + } + + const responseBody = await getResponseBody(response); + const responseHeader = getResponseHeader( + response, + options.responseHeader + ); + + const result: ApiResult = { + url, + ok: response.ok, + status: response.status, + statusText: response.statusText, + body: responseHeader ?? responseBody, + }; + + catchErrorCodes(options, result); + + resolve(result.body); + } + } catch (error) { + reject(error); + } + }); +}; diff --git a/js/src/sdk/client/index.ts b/js/src/sdk/client/index.ts index 0a2b84baed..1cb041de5c 100644 --- a/js/src/sdk/client/index.ts +++ b/js/src/sdk/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export * from './schemas.gen'; -export * from './services.gen'; -export * from './types.gen'; \ No newline at end of file +export * from "./schemas.gen"; +export * from "./services.gen"; +export * from "./types.gen"; diff --git a/js/src/sdk/client/schemas.gen.ts b/js/src/sdk/client/schemas.gen.ts index a83c6a5c02..d828a91ce7 100644 --- a/js/src/sdk/client/schemas.gen.ts +++ b/js/src/sdk/client/schemas.gen.ts @@ -1,3452 +1,3664 @@ // This file is auto-generated by @hey-api/openapi-ts export const $MemberInfoResDTO = { - properties: { - id: { - type: 'string' - }, - projectId: { - type: 'string' - }, - email: { - format: 'email', - type: 'string' - }, - name: { - type: 'string' - }, - role: { - type: 'string' - }, - metadata: {}, - createdAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - updatedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - deletedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - } - }, - type: 'object', - required: ['id', 'projectId', 'email', 'name', 'role', 'createdAt', 'updatedAt'], - description: 'Member information' + properties: { + id: { + type: "string", + }, + projectId: { + type: "string", + }, + email: { + format: "email", + type: "string", + }, + name: { + type: "string", + }, + role: { + type: "string", + }, + metadata: {}, + createdAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + }, + updatedAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + }, + deletedAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + }, + }, + type: "object", + required: [ + "id", + "projectId", + "email", + "name", + "role", + "createdAt", + "updatedAt", + ], + description: "Member information", } as const; export const $MagicLinkResDTO = { - properties: { - status: { - type: 'string' - } + properties: { + status: { + type: "string", }, - type: 'object', - required: ['status'] + }, + type: "object", + required: ["status"], } as const; export const $MagicLinkReqDTO = { - properties: { - email: { - format: 'email', - type: 'string', - description: 'The email of the user' - }, - verifyHost: { - type: 'string', - description: 'The frontend host of the user' - } + properties: { + email: { + format: "email", + type: "string", + description: "The email of the user", }, - type: 'object', - required: ['email', 'verifyHost'] + verifyHost: { + type: "string", + description: "The frontend host of the user", + }, + }, + type: "object", + required: ["email", "verifyHost"], } as const; export const $LogoutResDTO = { - properties: { - message: { - type: 'string', - description: 'Message confirming the logout' - } + properties: { + message: { + type: "string", + description: "Message confirming the logout", }, - type: 'object', - required: ['message'] + }, + type: "object", + required: ["message"], } as const; export const $VerifyMagicLinkReqDTO = { - properties: { - token: { - type: 'string', - description: 'The magic link token' - } + properties: { + token: { + type: "string", + description: "The magic link token", }, - type: 'object', - required: ['token'] + }, + type: "object", + required: ["token"], } as const; export const $VerifyMagicLinkDataDTO = { - properties: { - clientId: { - type: 'string' - }, - isValid: { - type: 'boolean' - }, - jwtToken: { - type: 'string' - }, - email: { - type: 'string', - format: 'email' - } + properties: { + clientId: { + type: "string", }, - type: 'object', - required: ['clientId', 'isValid', 'jwtToken', 'email'], - description: 'Data containing client and token information if verification is successful' + isValid: { + type: "boolean", + }, + jwtToken: { + type: "string", + }, + email: { + type: "string", + format: "email", + }, + }, + type: "object", + required: ["clientId", "isValid", "jwtToken", "email"], + description: + "Data containing client and token information if verification is successful", } as const; export const $VerifyMagicLinkResDTO = { - properties: { - message: { - type: 'string', - description: 'Message indicating the result of the verification' - }, - data: { - '$ref': '#/components/schemas/VerifyMagicLinkDataDTO' - } + properties: { + message: { + type: "string", + description: "Message indicating the result of the verification", }, - type: 'object', - required: ['message'] + data: { + $ref: "#/components/schemas/VerifyMagicLinkDataDTO", + }, + }, + type: "object", + required: ["message"], } as const; export const $IdentifyClientReqDTO = { - properties: { - hash: { - type: 'string', - description: 'The hash of the client' - }, - framework: { - type: 'string', - description: 'The framework used by the client' - } + properties: { + hash: { + type: "string", + description: "The hash of the client", }, - type: 'object', - required: ['hash'] + framework: { + type: "string", + description: "The framework used by the client", + }, + }, + type: "object", + required: ["hash"], } as const; export const $IdentifyClientResDTO = { - properties: { - clientId: { - type: 'string', - description: 'The client ID' - }, - apiKey: { - type: 'string', - description: 'The API key associated with the client' - }, - email: { - type: 'string', - description: 'The email associated with the client' - }, - orgId: { - type: 'string', - description: 'The organization ID associated with the client' - } + properties: { + clientId: { + type: "string", + description: "The client ID", + }, + apiKey: { + type: "string", + description: "The API key associated with the client", + }, + email: { + type: "string", + description: "The email associated with the client", }, - type: 'object', - required: ['clientId', 'apiKey', 'email', 'orgId'] + orgId: { + type: "string", + description: "The organization ID associated with the client", + }, + }, + type: "object", + required: ["clientId", "apiKey", "email", "orgId"], } as const; export const $UserGitUserInfo = { - properties: { - name: { - type: 'string' - }, - email: { - format: 'email', - type: 'string' - } + properties: { + name: { + type: "string", }, - type: 'object', - required: ['email'], - description: 'User Git information' + email: { + format: "email", + type: "string", + }, + }, + type: "object", + required: ["email"], + description: "User Git information", } as const; export const $TrackClientReqDTO = { - properties: { - framework: { - type: 'string', - description: 'The framework used by the client' - }, - mac_address: { - type: 'string', - description: 'The MAC address of the client device' - }, - user_git_user_info: { - '$ref': '#/components/schemas/UserGitUserInfo' - } + properties: { + framework: { + type: "string", + description: "The framework used by the client", + }, + mac_address: { + type: "string", + description: "The MAC address of the client device", + }, + user_git_user_info: { + $ref: "#/components/schemas/UserGitUserInfo", }, - type: 'object', - required: ['framework'] + }, + type: "object", + required: ["framework"], } as const; export const $TrackClientResDTO = { - properties: { - message: { - type: 'string', - description: 'Message indicating the result of the tracking operation' - } + properties: { + message: { + type: "string", + description: "Message indicating the result of the tracking operation", }, - type: 'object', - required: ['message'] + }, + type: "object", + required: ["message"], } as const; export const $DeleteRowAPIDTO = { - properties: { - status: { - type: 'string', - description: 'Status of the delete operation' - }, - count: { - type: 'number', - description: 'Number of records deleted' - } + properties: { + status: { + type: "string", + description: "Status of the delete operation", + }, + count: { + type: "number", + description: "Number of records deleted", }, - type: 'object', - required: ['status', 'count'] + }, + type: "object", + required: ["status", "count"], } as const; export const $ClientDTO = { - properties: { - autoId: { - type: 'number', - description: 'Auto-generated ID of the client' - }, - id: { - type: 'string', - description: 'Unique ID of the client' - }, - name: { - type: 'string', - description: 'Name of the client' - }, - email: { - type: 'string', - description: 'Email of the client' - }, - createdAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ], - description: 'Creation timestamp' - }, - updatedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ], - description: 'Last update timestamp' - }, - apiKey: { - type: 'string', - description: 'API key for the client' - }, - webhookURL: { - type: 'string', - description: 'Webhook URL for the client' - }, - eventWebhookURL: { - type: 'string', - description: 'Event webhook URL for the client' - }, - webhookSecret: { - type: 'string', - description: 'Secret for webhook authentication' - }, - triggersEnabled: { - type: 'boolean', - description: 'Whether triggers are enabled for the client' - }, - lastSubscribedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ], - description: 'Last subscription timestamp' - }, - plan: { - type: 'string', - description: "Client's subscription plan" - } - }, - type: 'object', - required: ['autoId', 'id', 'name', 'email', 'createdAt', 'updatedAt', 'triggersEnabled', 'plan'], - description: 'Client information' + properties: { + autoId: { + type: "number", + description: "Auto-generated ID of the client", + }, + id: { + type: "string", + description: "Unique ID of the client", + }, + name: { + type: "string", + description: "Name of the client", + }, + email: { + type: "string", + description: "Email of the client", + }, + createdAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + description: "Creation timestamp", + }, + updatedAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + description: "Last update timestamp", + }, + apiKey: { + type: "string", + description: "API key for the client", + }, + webhookURL: { + type: "string", + description: "Webhook URL for the client", + }, + eventWebhookURL: { + type: "string", + description: "Event webhook URL for the client", + }, + webhookSecret: { + type: "string", + description: "Secret for webhook authentication", + }, + triggersEnabled: { + type: "boolean", + description: "Whether triggers are enabled for the client", + }, + lastSubscribedAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + description: "Last subscription timestamp", + }, + plan: { + type: "string", + description: "Client's subscription plan", + }, + }, + type: "object", + required: [ + "autoId", + "id", + "name", + "email", + "createdAt", + "updatedAt", + "triggersEnabled", + "plan", + ], + description: "Client information", } as const; export const $ClientInfoResDTO = { - properties: { - client: { - '$ref': '#/components/schemas/ClientDTO' - }, - apiKey: { - type: 'string', - description: 'API key of the client' - } + properties: { + client: { + $ref: "#/components/schemas/ClientDTO", + }, + apiKey: { + type: "string", + description: "API key of the client", }, - type: 'object', - required: ['client', 'apiKey'] + }, + type: "object", + required: ["client", "apiKey"], } as const; export const $ProjectReqDTO = { - properties: { - name: { - type: 'string', - description: 'The name of the project' - } + properties: { + name: { + type: "string", + description: "The name of the project", }, - type: 'object', - required: ['name'] + }, + type: "object", + required: ["name"], } as const; export const $ProjectResDTO = { - properties: { - id: { - type: 'string', - description: 'The ID of the project' - }, - name: { - type: 'string', - description: 'The name of the project' - } + properties: { + id: { + type: "string", + description: "The ID of the project", + }, + name: { + type: "string", + description: "The name of the project", }, - type: 'object', - required: ['id', 'name'] + }, + type: "object", + required: ["id", "name"], } as const; export const $ProjectListResDTO = { - properties: { - items: { - items: { - type: 'object' - }, - type: 'array', - description: 'The list of projects' - } + properties: { + items: { + items: { + type: "object", + }, + type: "array", + description: "The list of projects", }, - type: 'object', - required: ['items'] + }, + type: "object", + required: ["items"], } as const; export const $InviteMemberReqDTO = { - properties: { - email: { - format: 'email', - type: 'string', - description: 'The email of the member' - }, - name: { - type: 'string', - description: 'The name of the member' - }, - verifyHost: { - type: 'string', - description: 'The host to verify the member' - }, - role: { - enum: ['admin', 'developer'], - type: 'string', - description: 'The role that will be assignied to the invited user' - } + properties: { + email: { + format: "email", + type: "string", + description: "The email of the member", + }, + name: { + type: "string", + description: "The name of the member", }, - type: 'object', - required: ['email', 'name', 'verifyHost'] + verifyHost: { + type: "string", + description: "The host to verify the member", + }, + role: { + enum: ["admin", "developer"], + type: "string", + description: "The role that will be assignied to the invited user", + }, + }, + type: "object", + required: ["email", "name", "verifyHost"], } as const; export const $MemberResDTO = { - properties: { - email: { - type: 'string', - description: 'The email of the member' - }, - id: { - type: 'string', - description: 'The uuid identifier for the member' - }, - name: { - type: 'string', - description: 'The name of the member' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The creation date of the member record' - }, - role: { - enum: ['admin', 'developer'], - type: 'string', - description: 'The role that is assigned to the member' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The last update date of the member record' - } + properties: { + email: { + type: "string", + description: "The email of the member", }, - type: 'object', - required: ['email', 'id', 'name', 'role'] + id: { + type: "string", + description: "The uuid identifier for the member", + }, + name: { + type: "string", + description: "The name of the member", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The creation date of the member record", + }, + role: { + enum: ["admin", "developer"], + type: "string", + description: "The role that is assigned to the member", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The last update date of the member record", + }, + }, + type: "object", + required: ["email", "id", "name", "role"], } as const; export const $UpdateMemberReqDTO = { - properties: { - memberId: { - type: 'string', - description: 'The uuid identifier for the member' - }, - role: { - enum: ['admin', 'developer'], - type: 'string', - description: 'The role that is assigned to the member' - } + properties: { + memberId: { + type: "string", + description: "The uuid identifier for the member", }, - type: 'object', - required: ['memberId', 'role'] + role: { + enum: ["admin", "developer"], + type: "string", + description: "The role that is assigned to the member", + }, + }, + type: "object", + required: ["memberId", "role"], } as const; export const $GenerateAPIKeyReqDTO = { - properties: { - name: { - type: 'string', - description: 'The name of the API key to be generated' - } + properties: { + name: { + type: "string", + description: "The name of the API key to be generated", }, - type: 'object', - required: ['name'] + }, + type: "object", + required: ["name"], } as const; export const $APIKeyResDTO = { - properties: { - id: { - type: 'string', - description: 'The ID of the API key' - }, - name: { - type: 'string', - description: 'The name of the API key' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The creation date of the API key' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The last update date of the API key' - }, - key: { - type: 'string', - description: 'The generated API key' - }, - isHidden: { - type: 'boolean', - description: 'Whether the API key is hidden' - }, - lastUsed: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The last used date of the API key' - }, - member: { - type: 'object', - description: 'The member of the API key' - } - }, - type: 'object', - required: ['id', 'name', 'createdAt', 'updatedAt', 'key', 'isHidden', 'member'] + properties: { + id: { + type: "string", + description: "The ID of the API key", + }, + name: { + type: "string", + description: "The name of the API key", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The creation date of the API key", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The last update date of the API key", + }, + key: { + type: "string", + description: "The generated API key", + }, + isHidden: { + type: "boolean", + description: "Whether the API key is hidden", + }, + lastUsed: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The last used date of the API key", + }, + member: { + type: "object", + description: "The member of the API key", + }, + }, + type: "object", + required: [ + "id", + "name", + "createdAt", + "updatedAt", + "key", + "isHidden", + "member", + ], } as const; export const $DeleteAPIKeyReqDTO = { - properties: { - id: { - type: 'string', - description: 'The ID of the API key to be deleted' - } + properties: { + id: { + type: "string", + description: "The ID of the API key to be deleted", }, - type: 'object', - required: ['id'] + }, + type: "object", + required: ["id"], } as const; export const $DeleteAPIKeyResponseDTO = { - properties: { - deleted: { - type: 'boolean', - description: 'The status of the delete operation' - } + properties: { + deleted: { + type: "boolean", + description: "The status of the delete operation", }, - type: 'object', - required: ['deleted'] + }, + type: "object", + required: ["deleted"], } as const; export const $SingleAppInfoResDTO = { - properties: { - appId: { - type: 'string', - description: 'The unique identifier for the app' - }, - key: { - type: 'string', - description: 'The key of the app' - }, - name: { - type: 'string', - description: 'The name of the app' - }, - description: { - type: 'string', - description: 'The description of the app' - }, - logo: { - type: 'string', - description: 'The logo of the app' - }, - categories: { - items: { - type: 'string' - }, - type: 'array', - description: 'The categories of the app' - }, - path: { - type: 'string', - description: 'The path of the app' - }, - docs: { - type: 'string', - description: 'The documentation URL of the app' - }, - configuration_docs_text: { - type: 'string', - description: 'The configuration documentation text of the app' - }, - status: { - type: 'string', - description: 'The status of the app' - }, - documentation_doc_text: { - type: 'string', - description: 'The documentation text of the app' - }, - testConnectors: { - items: { - type: 'object' - }, - type: 'array', - description: 'The test connectors of the app' - }, - no_auth: { - type: 'boolean', - description: 'Indicates if the app has no authentication' - }, - auth_schemes: { - items: { - type: 'object' - }, - type: 'array', - description: 'The authentication schemes of the app' - }, - meta: { - description: 'The metadata of the app' - }, - yaml: { - description: 'The yaml of the app' - } - }, - type: 'object', - required: ['appId', 'key', 'name', 'description'] + properties: { + appId: { + type: "string", + description: "The unique identifier for the app", + }, + key: { + type: "string", + description: "The key of the app", + }, + name: { + type: "string", + description: "The name of the app", + }, + description: { + type: "string", + description: "The description of the app", + }, + logo: { + type: "string", + description: "The logo of the app", + }, + categories: { + items: { + type: "string", + }, + type: "array", + description: "The categories of the app", + }, + path: { + type: "string", + description: "The path of the app", + }, + docs: { + type: "string", + description: "The documentation URL of the app", + }, + configuration_docs_text: { + type: "string", + description: "The configuration documentation text of the app", + }, + status: { + type: "string", + description: "The status of the app", + }, + documentation_doc_text: { + type: "string", + description: "The documentation text of the app", + }, + testConnectors: { + items: { + type: "object", + }, + type: "array", + description: "The test connectors of the app", + }, + no_auth: { + type: "boolean", + description: "Indicates if the app has no authentication", + }, + auth_schemes: { + items: { + type: "object", + }, + type: "array", + description: "The authentication schemes of the app", + }, + meta: { + description: "The metadata of the app", + }, + yaml: { + description: "The yaml of the app", + }, + }, + type: "object", + required: ["appId", "key", "name", "description"], } as const; export const $AddToolsReqDTO = { - properties: { - name: { - type: 'string', - description: 'The name of the tool' - }, - openApiSpecYaml: { - type: 'string', - description: 'The OpenAPI specification in YAML format' - }, - integrationYaml: { - type: 'string', - description: 'The integration details in YAML format' - } + properties: { + name: { + type: "string", + description: "The name of the tool", + }, + openApiSpecYaml: { + type: "string", + description: "The OpenAPI specification in YAML format", }, - type: 'object', - required: ['name', 'openApiSpecYaml', 'integrationYaml'] + integrationYaml: { + type: "string", + description: "The integration details in YAML format", + }, + }, + type: "object", + required: ["name", "openApiSpecYaml", "integrationYaml"], } as const; export const $OpenAPISpecListResDTO = { - properties: { - id: { - type: 'string', - description: 'Unique identifier for the OpenAPI spec' - }, - name: { - type: 'string', - description: 'Name of the OpenAPI spec' - }, - clientId: { - type: 'string', - description: 'Client identifier' - }, - lastSyncAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Last synchronization date and time', - format: 'date-time' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Creation date and time', - format: 'date-time' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Last update date and time', - format: 'date-time' - }, - status: { - enum: ['initialized', 'running', 'caching', 'cancelled', 'finished', 'exited'], - type: 'string', - description: 'The job status of the app' - }, - state: { - enum: ['preprocess', 'validate', 'prepare', 'build', 'push', 'load', 'finish'], - type: 'string', - description: 'Current state of the app FSM' - } - }, - type: 'object', - required: ['id', 'name', 'clientId', 'lastSyncAt', 'createdAt', 'updatedAt'] + properties: { + id: { + type: "string", + description: "Unique identifier for the OpenAPI spec", + }, + name: { + type: "string", + description: "Name of the OpenAPI spec", + }, + clientId: { + type: "string", + description: "Client identifier", + }, + lastSyncAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Last synchronization date and time", + format: "date-time", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Creation date and time", + format: "date-time", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Last update date and time", + format: "date-time", + }, + status: { + enum: [ + "initialized", + "running", + "caching", + "cancelled", + "finished", + "exited", + ], + type: "string", + description: "The job status of the app", + }, + state: { + enum: [ + "preprocess", + "validate", + "prepare", + "build", + "push", + "load", + "finish", + ], + type: "string", + description: "Current state of the app FSM", + }, + }, + type: "object", + required: ["id", "name", "clientId", "lastSyncAt", "createdAt", "updatedAt"], } as const; export const $AddRepoURLResDTO = { - properties: { - repoUrl: { - type: 'string', - description: 'Repository URL' - } + properties: { + repoUrl: { + type: "string", + description: "Repository URL", }, - type: 'object', - required: ['repoUrl'] + }, + type: "object", + required: ["repoUrl"], } as const; export const $DeleteToolsReqDTO = { - properties: { - name: { - type: 'string', - description: 'Name of the tool' - } + properties: { + name: { + type: "string", + description: "Name of the tool", }, - type: 'object', - required: ['name'] + }, + type: "object", + required: ["name"], } as const; export const $DeleteToolsResDTO = { - properties: { - message: { - type: 'string', - description: 'Message indicating successful deletion of tools' - } + properties: { + message: { + type: "string", + description: "Message indicating successful deletion of tools", }, - type: 'object', - required: ['message'] + }, + type: "object", + required: ["message"], } as const; export const $AddToolsRequestDTO = { - properties: { - name: { - type: 'string', - description: 'The name of the tool' - }, - open_api_spec_yaml: { - type: 'string', - description: 'The OpenAPI specification in YAML format' - }, - integration_yaml: { - type: 'string', - description: 'The integration details in YAML format' - } + properties: { + name: { + type: "string", + description: "The name of the tool", }, - type: 'object', - required: ['name', 'open_api_spec_yaml', 'integration_yaml'] + open_api_spec_yaml: { + type: "string", + description: "The OpenAPI specification in YAML format", + }, + integration_yaml: { + type: "string", + description: "The integration details in YAML format", + }, + }, + type: "object", + required: ["name", "open_api_spec_yaml", "integration_yaml"], } as const; export const $AddRepoURLReqDTO = { - properties: { - repoUrl: { - type: 'string', - description: 'Repository URL' - } + properties: { + repoUrl: { + type: "string", + description: "Repository URL", }, - type: 'object', - required: ['repoUrl'] + }, + type: "object", + required: ["repoUrl"], } as const; export const $AppQueryDTO = { - properties: { - category: { - type: 'string', - description: 'Category of the app' - }, - additionalFields: { - type: 'string', - description: 'Additional fields to include in the response' - }, - includeLocal: { - type: 'string', - description: "Enter 'true' or 'false'" - } + properties: { + category: { + type: "string", + description: "Category of the app", }, - type: 'object' + additionalFields: { + type: "string", + description: "Additional fields to include in the response", + }, + includeLocal: { + type: "string", + description: "Enter 'true' or 'false'", + }, + }, + type: "object", } as const; export const $AppInfoResponseDto = { - properties: { - appId: { - type: 'string', - description: 'The ID of the app' - }, - key: { - type: 'string', - description: 'The key of the app' - }, - name: { - type: 'string', - description: 'The name of the app' - }, - description: { - type: 'string', - description: 'The description of the app' - }, - logo: { - type: 'string', - description: 'The logo of the app' - }, - categories: { - items: { - type: 'object' - }, - type: 'string', - description: 'The categories of the app' - }, - tags: { - items: { - type: 'object' - }, - type: 'string', - description: 'The tags of the app' - }, - auth_schemes: { - description: 'The authentication schemes of the app' - }, - enabled: { - type: 'boolean', - description: 'Indicates if the app is enabled' - }, - no_auth: { - type: 'boolean', - description: 'Indicates if the app has no authentication' - } - }, - type: 'object', - required: ['appId', 'key', 'name', 'description', 'logo', 'categories', 'enabled'] + properties: { + appId: { + type: "string", + description: "The ID of the app", + }, + key: { + type: "string", + description: "The key of the app", + }, + name: { + type: "string", + description: "The name of the app", + }, + description: { + type: "string", + description: "The description of the app", + }, + logo: { + type: "string", + description: "The logo of the app", + }, + categories: { + items: { + type: "object", + }, + type: "string", + description: "The categories of the app", + }, + tags: { + items: { + type: "object", + }, + type: "string", + description: "The tags of the app", + }, + auth_schemes: { + description: "The authentication schemes of the app", + }, + enabled: { + type: "boolean", + description: "Indicates if the app is enabled", + }, + no_auth: { + type: "boolean", + description: "Indicates if the app has no authentication", + }, + }, + type: "object", + required: [ + "appId", + "key", + "name", + "description", + "logo", + "categories", + "enabled", + ], } as const; export const $AppListResDTO = { - properties: { - items: { - items: { - '$ref': '#/components/schemas/AppInfoResponseDto' - }, - type: 'array', - description: 'List of app details' - }, - totalPages: { - type: 'number', - description: 'Total number of pages' - } + properties: { + items: { + items: { + $ref: "#/components/schemas/AppInfoResponseDto", + }, + type: "array", + description: "List of app details", }, - type: 'object', - required: ['items', 'totalPages'] + totalPages: { + type: "number", + description: "Total number of pages", + }, + }, + type: "object", + required: ["items", "totalPages"], } as const; export const $ExpectedInputFieldsDTO = { - properties: { - name: { - type: 'string', - description: 'Name of the field' - }, - type: { - type: 'string', - description: 'Type of the field' - }, - description: { - type: 'string', - description: 'Description of the field' - }, - display_name: { - type: 'string', - description: 'Display name of the field' - }, - default: { - type: 'object', - description: 'Default value of the field' - }, - required: { - type: 'boolean', - description: 'Whether the field is required' - }, - expected_from_customer: { - type: 'boolean', - description: 'Whether the field is expected from customer' - }, - is_secret: { - type: 'boolean', - description: 'Whether the field is a secret' - } - }, - type: 'object', - required: ['name', 'type', 'description', 'display_name', 'default', 'required', 'expected_from_customer', 'is_secret'] + properties: { + name: { + type: "string", + description: "Name of the field", + }, + type: { + type: "string", + description: "Type of the field", + }, + description: { + type: "string", + description: "Description of the field", + }, + display_name: { + type: "string", + description: "Display name of the field", + }, + default: { + type: "object", + description: "Default value of the field", + }, + required: { + type: "boolean", + description: "Whether the field is required", + }, + expected_from_customer: { + type: "boolean", + description: "Whether the field is expected from customer", + }, + is_secret: { + type: "boolean", + description: "Whether the field is a secret", + }, + }, + type: "object", + required: [ + "name", + "type", + "description", + "display_name", + "default", + "required", + "expected_from_customer", + "is_secret", + ], } as const; export const $GetConnectorInfoResDTO = { - properties: { - id: { - type: 'string', - description: 'Unique identifier of the connector' - }, - authScheme: { - type: 'string', - description: 'Authentication scheme used by the connector' - }, - name: { - type: 'string', - description: 'Name of the connector' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Creation date of the connector' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Last update date of the connector' - }, - enabled: { - type: 'boolean', - description: 'Flag to indicate if the connector is currently enabled' - }, - deleted: { - type: 'boolean', - description: 'Flag to indicate if the connector has been deleted' - }, - appId: { - type: 'string', - description: 'Application ID associated with the connector' - }, - defaultConnectorId: { - type: 'string', - description: 'Default connector ID if one exists' - }, - authConfig: { - type: 'object', - description: 'Authentication configuration with sensitive data obscured' - }, - expectedInputFields: { - items: { - '$ref': '#/components/schemas/ExpectedInputFieldsDTO' - }, - type: 'array', - description: 'List of required fields expected from the customer' - }, - logo: { - type: 'string', - description: 'Logo URL of the application associated with the connector' - }, - appName: { - type: 'string', - description: 'Name of the application associated with the connector' - }, - useComposioAuth: { - type: 'boolean', - description: 'Flag to indicate if Composio authentication is used' - } - }, - type: 'object', - required: ['enabled', 'appId', 'authConfig', 'expectedInputFields', 'logo', 'appName', 'useComposioAuth'] + properties: { + id: { + type: "string", + description: "Unique identifier of the connector", + }, + authScheme: { + type: "string", + description: "Authentication scheme used by the connector", + }, + name: { + type: "string", + description: "Name of the connector", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Creation date of the connector", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Last update date of the connector", + }, + enabled: { + type: "boolean", + description: "Flag to indicate if the connector is currently enabled", + }, + deleted: { + type: "boolean", + description: "Flag to indicate if the connector has been deleted", + }, + appId: { + type: "string", + description: "Application ID associated with the connector", + }, + defaultConnectorId: { + type: "string", + description: "Default connector ID if one exists", + }, + authConfig: { + type: "object", + description: "Authentication configuration with sensitive data obscured", + }, + expectedInputFields: { + items: { + $ref: "#/components/schemas/ExpectedInputFieldsDTO", + }, + type: "array", + description: "List of required fields expected from the customer", + }, + logo: { + type: "string", + description: "Logo URL of the application associated with the connector", + }, + appName: { + type: "string", + description: "Name of the application associated with the connector", + }, + useComposioAuth: { + type: "boolean", + description: "Flag to indicate if Composio authentication is used", + }, + }, + type: "object", + required: [ + "enabled", + "appId", + "authConfig", + "expectedInputFields", + "logo", + "appName", + "useComposioAuth", + ], } as const; export const $AuthConfigDTO = { - properties: { - scopes: { - items: { - type: 'string' - }, - type: 'array' - }, - user_scopes: { - items: { - type: 'string' - }, - type: 'array' - } + properties: { + scopes: { + items: { + type: "string", + }, + type: "array", + }, + user_scopes: { + items: { + type: "string", + }, + type: "array", }, - type: 'object', - description: 'Authentication configuration' + }, + type: "object", + description: "Authentication configuration", } as const; export const $CreateConnectorPayloadDTO = { - properties: { - name: { - type: 'string', - description: 'Name of the connector' - }, - authScheme: { - type: 'string', - description: 'Authentication scheme' - }, - authConfig: { - '$ref': '#/components/schemas/AuthConfigDTO' - }, - useComposioAuth: { - type: 'boolean', - description: 'Flag to indicate if Composio authentication should be used', - anyOf: [ - { - type: 'boolean' - } - ] - }, - appId: { - type: 'string', - description: 'Composio App UUID to be used for authentication. Either specify this or appName' - }, - appName: { - type: 'string', - description: 'Name of the app to be used for authentication. Either specify this or appId' + properties: { + name: { + type: "string", + description: "Name of the connector", + }, + authScheme: { + type: "string", + description: "Authentication scheme", + }, + authConfig: { + $ref: "#/components/schemas/AuthConfigDTO", + }, + useComposioAuth: { + type: "boolean", + description: "Flag to indicate if Composio authentication should be used", + anyOf: [ + { + type: "boolean", }, - forceNewIntegration: { - type: 'boolean', - description: 'Flag to force new integration' - } + ], + }, + appId: { + type: "string", + description: + "Composio App UUID to be used for authentication. Either specify this or appName", + }, + appName: { + type: "string", + description: + "Name of the app to be used for authentication. Either specify this or appId", + }, + forceNewIntegration: { + type: "boolean", + description: "Flag to force new integration", }, - type: 'object', - required: ['name'] + }, + type: "object", + required: ["name"], } as const; export const $PatchConnectorReqDTO = { - properties: { - authConfig: { - type: 'object', - description: 'Authentication configuration for the connector' - }, - enabled: { - type: 'boolean', - description: 'Flag to indicate if the connector is enabled' - } + properties: { + authConfig: { + type: "object", + description: "Authentication configuration for the connector", + }, + enabled: { + type: "boolean", + description: "Flag to indicate if the connector is enabled", }, - type: 'object' + }, + type: "object", } as const; export const $PatchConnectorResDTO = { - properties: { - status: { - type: 'string', - description: 'Status of the patch operation' - } + properties: { + status: { + type: "string", + description: "Status of the patch operation", }, - type: 'object', - required: ['status'] + }, + type: "object", + required: ["status"], } as const; export const $ConnectorListItemDTO = { - properties: { - appName: { - type: 'string', - description: 'Application name associated with the connector' - }, - _count: { - type: 'object', - description: 'Count of connections for the connector' - }, - connections: { - items: { - type: 'object' - }, - type: 'array', - description: 'List of connections with their details and request logs count' - }, - id: { - type: 'string', - description: 'Unique identifier of the connector' - }, - member: { - '$ref': '#/components/schemas/MemberInfoResDTO' - }, - name: { - type: 'string', - description: 'Name of the connector' - }, - authScheme: { - type: 'string', - description: 'Authentication scheme used by the connector' - }, - createdAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ], - description: 'Creation date of the connector' - }, - updatedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ], - description: 'Last update date of the connector' - }, - enabled: { - type: 'boolean', - description: 'Flag to indicate if the connector is enabled' - }, - deleted: { - type: 'boolean', - description: 'Flag to indicate if the connector is deleted' - }, - appId: { - type: 'string', - description: 'App ID associated with the connector' - }, - defaultConnectorId: { - type: 'string', - description: 'Default connector ID if available' - } - }, - type: 'object', - required: ['appName', '_count', 'connections', 'id', 'member', 'name', 'authScheme', 'createdAt', 'updatedAt', 'enabled', 'appId'], - description: 'List of connectors' + properties: { + appName: { + type: "string", + description: "Application name associated with the connector", + }, + _count: { + type: "object", + description: "Count of connections for the connector", + }, + connections: { + items: { + type: "object", + }, + type: "array", + description: + "List of connections with their details and request logs count", + }, + id: { + type: "string", + description: "Unique identifier of the connector", + }, + member: { + $ref: "#/components/schemas/MemberInfoResDTO", + }, + name: { + type: "string", + description: "Name of the connector", + }, + authScheme: { + type: "string", + description: "Authentication scheme used by the connector", + }, + createdAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + description: "Creation date of the connector", + }, + updatedAt: { + oneOf: [ + { + format: "date", + type: "string", + }, + { + format: "date-time", + type: "string", + }, + ], + description: "Last update date of the connector", + }, + enabled: { + type: "boolean", + description: "Flag to indicate if the connector is enabled", + }, + deleted: { + type: "boolean", + description: "Flag to indicate if the connector is deleted", + }, + appId: { + type: "string", + description: "App ID associated with the connector", + }, + defaultConnectorId: { + type: "string", + description: "Default connector ID if available", + }, + }, + type: "object", + required: [ + "appName", + "_count", + "connections", + "id", + "member", + "name", + "authScheme", + "createdAt", + "updatedAt", + "enabled", + "appId", + ], + description: "List of connectors", } as const; export const $GetConnectorListResDTO = { - properties: { - items: { - items: { - type: 'object' - }, - type: 'array' - }, - totalPages: { - type: 'number', - description: 'Total number of pages available' - }, - page: { - type: 'number', - description: 'Current page number' - } + properties: { + items: { + items: { + type: "object", + }, + type: "array", + }, + totalPages: { + type: "number", + description: "Total number of pages available", + }, + page: { + type: "number", + description: "Current page number", }, - type: 'object', - required: ['items', 'totalPages', 'page'] + }, + type: "object", + required: ["items", "totalPages", "page"], } as const; export const $PageInfo = { - properties: { - total: { - minimum: 0, - type: 'integer' - }, - page: { - minimum: 1, - type: 'integer' - }, - pageSize: { - minimum: 1, - type: 'integer' - }, - totalPages: { - minimum: 1, - type: 'integer' - } + properties: { + total: { + minimum: 0, + type: "integer", }, - type: 'object', - required: ['total', 'page', 'pageSize', 'totalPages'] + page: { + minimum: 1, + type: "integer", + }, + pageSize: { + minimum: 1, + type: "integer", + }, + totalPages: { + minimum: 1, + type: "integer", + }, + }, + type: "object", + required: ["total", "page", "pageSize", "totalPages"], } as const; export const $ConnectionWithAppData = { - properties: { - id: { - type: 'string' - }, - integrationId: { - type: 'string' - }, - clientUniqueUserId: { - type: 'string' - }, - status: { - type: 'string' - }, - data: { - type: 'object' - }, - deleted: { - type: 'boolean' - }, - enabled: { - type: 'boolean' - }, - createdAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - updatedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - appUniqueId: { - type: 'string' - }, - appName: { - type: 'string' + properties: { + id: { + type: "string", + }, + integrationId: { + type: "string", + }, + clientUniqueUserId: { + type: "string", + }, + status: { + type: "string", + }, + data: { + type: "object", + }, + deleted: { + type: "boolean", + }, + enabled: { + type: "boolean", + }, + createdAt: { + oneOf: [ + { + format: "date", + type: "string", }, - logo: { - type: 'string' + { + format: "date-time", + type: "string", }, - authConfig: { - type: 'object' + ], + }, + updatedAt: { + oneOf: [ + { + format: "date", + type: "string", }, - member: { - items: { - '$ref': '#/components/schemas/MemberInfoResDTO' - }, - type: 'object' + { + format: "date-time", + type: "string", }, - labels: { - items: { - type: 'string' - }, - type: 'array' - } + ], + }, + appUniqueId: { + type: "string", + }, + appName: { + type: "string", }, - type: 'object', - required: ['id', 'integrationId', 'status', 'createdAt', 'updatedAt', 'appUniqueId', 'appName', 'member'] + logo: { + type: "string", + }, + authConfig: { + type: "object", + }, + member: { + items: { + $ref: "#/components/schemas/MemberInfoResDTO", + }, + type: "object", + }, + labels: { + items: { + type: "string", + }, + type: "array", + }, + }, + type: "object", + required: [ + "id", + "integrationId", + "status", + "createdAt", + "updatedAt", + "appUniqueId", + "appName", + "member", + ], } as const; export const $GetConnectionsResult = { - properties: { - connections: { - items: { - '$ref': '#/components/schemas/ConnectionWithAppData' - }, - type: 'array' - }, - pageInfo: { - '$ref': '#/components/schemas/PageInfo' - } + properties: { + connections: { + items: { + $ref: "#/components/schemas/ConnectionWithAppData", + }, + type: "array", + }, + pageInfo: { + $ref: "#/components/schemas/PageInfo", }, - type: 'object', - required: ['connections', 'pageInfo'] + }, + type: "object", + required: ["connections", "pageInfo"], } as const; export const $ConnectionParams = { - properties: { - integrationId: { - type: 'string' - }, - connectionParams: { - type: 'object' - }, - isDisabled: { - type: 'boolean' - }, - invocationCount: { - type: 'number' - }, - id: { - type: 'string' - }, - clientUniqueUserId: { - type: 'string' - }, - status: { - type: 'string' - }, - data: { - type: 'object' - }, - deleted: { - type: 'boolean' - }, - enabled: { - type: 'boolean' - }, - createdAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - updatedAt: { - oneOf: [ - { - format: 'date', - type: 'string' - }, - { - format: 'date-time', - type: 'string' - } - ] - }, - appUniqueId: { - type: 'string' - }, - appName: { - type: 'string' + properties: { + integrationId: { + type: "string", + }, + connectionParams: { + type: "object", + }, + isDisabled: { + type: "boolean", + }, + invocationCount: { + type: "number", + }, + id: { + type: "string", + }, + clientUniqueUserId: { + type: "string", + }, + status: { + type: "string", + }, + data: { + type: "object", + }, + deleted: { + type: "boolean", + }, + enabled: { + type: "boolean", + }, + createdAt: { + oneOf: [ + { + format: "date", + type: "string", }, - logo: { - type: 'string' + { + format: "date-time", + type: "string", }, - authConfig: { - type: 'object' + ], + }, + updatedAt: { + oneOf: [ + { + format: "date", + type: "string", }, - member: { - items: { - '$ref': '#/components/schemas/MemberInfoResDTO' - }, - type: 'object' + { + format: "date-time", + type: "string", }, - labels: { - items: { - type: 'string' - }, - type: 'array' - } + ], }, - type: 'object', - required: ['integrationId', 'isDisabled', 'invocationCount', 'id', 'status', 'createdAt', 'updatedAt', 'appUniqueId', 'appName', 'member'] + appUniqueId: { + type: "string", + }, + appName: { + type: "string", + }, + logo: { + type: "string", + }, + authConfig: { + type: "object", + }, + member: { + items: { + $ref: "#/components/schemas/MemberInfoResDTO", + }, + type: "object", + }, + labels: { + items: { + type: "string", + }, + type: "array", + }, + }, + type: "object", + required: [ + "integrationId", + "isDisabled", + "invocationCount", + "id", + "status", + "createdAt", + "updatedAt", + "appUniqueId", + "appName", + "member", + ], } as const; export const $ToggleConnectedAccountResponseDTO = { - properties: { - status: { - type: 'string' - } + properties: { + status: { + type: "string", }, - type: 'object', - required: ['status'] + }, + type: "object", + required: ["status"], } as const; export const $ConnectionParamsHeaders = { - properties: { - Authorization: { - type: 'string' - }, - 'x-request-id': { - type: 'string' - } + properties: { + Authorization: { + type: "string", }, - type: 'object' + "x-request-id": { + type: "string", + }, + }, + type: "object", } as const; export const $ConnectionParamsForAccount = { - properties: { - scope: { - type: 'string' - }, - scopes: { - type: 'string' - }, - id_token: { - type: 'string' - }, - client_id: { - type: 'string' - }, - expires_in: { - type: 'string' - }, - token_type: { - type: 'string' - }, - callback_url: { - type: 'string' - }, - client_secret: { - type: 'string' - }, - code_verifier: { - type: 'string' - }, - refresh_token: { - type: 'string' - }, - headers: { - type: 'object' - }, - queryParams: { - type: 'object' - }, - base_url: { - type: 'string' - } + properties: { + scope: { + type: "string", + }, + scopes: { + type: "string", + }, + id_token: { + type: "string", }, - type: 'object' + client_id: { + type: "string", + }, + expires_in: { + type: "string", + }, + token_type: { + type: "string", + }, + callback_url: { + type: "string", + }, + client_secret: { + type: "string", + }, + code_verifier: { + type: "string", + }, + refresh_token: { + type: "string", + }, + headers: { + type: "object", + }, + queryParams: { + type: "object", + }, + base_url: { + type: "string", + }, + }, + type: "object", } as const; export const $MetaApp = { - properties: { - get_current_user_endpoint: { - type: 'string' - } + properties: { + get_current_user_endpoint: { + type: "string", }, - type: 'object', - required: ['get_current_user_endpoint'] + }, + type: "object", + required: ["get_current_user_endpoint"], } as const; export const $Meta = { - properties: { - app: { - type: 'object' - } + properties: { + app: { + type: "object", }, - type: 'object', - required: ['app'] + }, + type: "object", + required: ["app"], } as const; export const $ConnectedAccountResponseDTO = { - properties: { - integrationId: { - type: 'string' - }, - appUniqueId: { - type: 'string' - }, - memberInfo: { - '$ref': '#/components/schemas/MemberInfoResDTO' - }, - meta: { - '$ref': '#/components/schemas/Meta' - }, - isDisabled: { - type: 'boolean' - }, - id: { - type: 'string' - }, - clientUniqueUserId: { - type: 'string' - }, - appName: { - type: 'string' - }, - entityId: { - type: 'string' - }, - status: { - type: 'string' - }, - enabled: { - type: 'boolean' - }, - createdAt: { - type: 'string' - }, - updatedAt: { - type: 'string' - } + properties: { + integrationId: { + type: "string", + }, + appUniqueId: { + type: "string", + }, + memberInfo: { + $ref: "#/components/schemas/MemberInfoResDTO", + }, + meta: { + $ref: "#/components/schemas/Meta", + }, + isDisabled: { + type: "boolean", + }, + id: { + type: "string", + }, + clientUniqueUserId: { + type: "string", + }, + appName: { + type: "string", + }, + entityId: { + type: "string", }, - type: 'object', - required: ['integrationId', 'appUniqueId', 'id', 'clientUniqueUserId', 'appName', 'entityId', 'status', 'createdAt', 'updatedAt'] + status: { + type: "string", + }, + enabled: { + type: "boolean", + }, + createdAt: { + type: "string", + }, + updatedAt: { + type: "string", + }, + }, + type: "object", + required: [ + "integrationId", + "appUniqueId", + "id", + "clientUniqueUserId", + "appName", + "entityId", + "status", + "createdAt", + "updatedAt", + ], } as const; export const $GetConnectionsResponseDto = { - properties: { - items: { - items: { - '$ref': '#/components/schemas/ConnectionParams' - }, - type: 'array' - }, - totalPages: { - type: 'number' - }, - page: { - type: 'number' - } + properties: { + items: { + items: { + $ref: "#/components/schemas/ConnectionParams", + }, + type: "array", + }, + totalPages: { + type: "number", + }, + page: { + type: "number", }, - type: 'object', - required: ['items', 'totalPages', 'page'] + }, + type: "object", + required: ["items", "totalPages", "page"], } as const; export const $GetConnectionInfoResponseDTO = { - properties: { - base_url: { - type: 'string' - }, - parameters: { - items: { - '$ref': '#/components/schemas/Parameter' - }, - type: 'array' - }, - body: { - type: 'object' - } + properties: { + base_url: { + type: "string", + }, + parameters: { + items: { + $ref: "#/components/schemas/Parameter", + }, + type: "array", + }, + body: { + type: "object", }, - type: 'object', - required: ['base_url', 'parameters', 'body'] + }, + type: "object", + required: ["base_url", "parameters", "body"], } as const; export const $Parameter = { - properties: { - name: { - type: 'string', - description: "The name of the parameter. For example, 'x-api-key', 'Content-Type', etc.," - }, - in: { - enum: ['query', 'header'], - type: 'string', - description: "The location of the parameter. Can be 'query' or 'header'." - }, - value: { - type: 'string', - description: "The value of the parameter. For example, '1234567890', 'application/json', etc.," - } + properties: { + name: { + type: "string", + description: + "The name of the parameter. For example, 'x-api-key', 'Content-Type', etc.,", + }, + in: { + enum: ["query", "header"], + type: "string", + description: "The location of the parameter. Can be 'query' or 'header'.", }, - type: 'object', - required: ['name', 'in', 'value'] + value: { + type: "string", + description: + "The value of the parameter. For example, '1234567890', 'application/json', etc.,", + }, + }, + type: "object", + required: ["name", "in", "value"], } as const; export const $Data = { - properties: { - field1: { - type: 'string' - }, - field2: { - type: 'string' - } + properties: { + field1: { + type: "string", }, - type: 'object', - required: ['field1', 'field2'] + field2: { + type: "string", + }, + }, + type: "object", + required: ["field1", "field2"], } as const; export const $AdditionalInfo = { - properties: { - meta: { - type: 'string' - } + properties: { + meta: { + type: "string", }, - type: 'object', - required: ['meta'] + }, + type: "object", + required: ["meta"], } as const; export const $GetConnectionsQueryDto = { - properties: { - page: { - type: 'number' - }, - pageSize: { - type: 'number' - }, - appNames: { - type: 'string' - }, - integrationId: { - type: 'string' - }, - connectionId: { - type: 'string' - }, - user_uuid: { - type: 'string' - }, - showActiveOnly: { - type: 'boolean' - }, - status: { - type: 'string' - }, - showDisabled: { - type: 'boolean' - }, - labels: { - items: { - type: 'string' - }, - type: 'array' - } + properties: { + page: { + type: "number", + }, + pageSize: { + type: "number", + }, + appNames: { + type: "string", + }, + integrationId: { + type: "string", }, - type: 'object' + connectionId: { + type: "string", + }, + user_uuid: { + type: "string", + }, + showActiveOnly: { + type: "boolean", + }, + status: { + type: "string", + }, + showDisabled: { + type: "boolean", + }, + labels: { + items: { + type: "string", + }, + type: "array", + }, + }, + type: "object", } as const; export const $InitiateConnectionPayloadDto = { - properties: { - data: { - type: 'object' - }, - integrationId: { - minLength: 1, - type: 'string' - }, - redirectUri: { - type: 'string' - }, - userUuid: { - type: 'string' - }, - entityId: { - type: 'string' - }, - labels: { - items: { - type: 'string' - }, - type: 'array' - } + properties: { + data: { + type: "object", + }, + integrationId: { + minLength: 1, + type: "string", + }, + redirectUri: { + type: "string", + }, + userUuid: { + type: "string", + }, + entityId: { + type: "string", }, - type: 'object', - required: ['data', 'integrationId'] + labels: { + items: { + type: "string", + }, + type: "array", + }, + }, + type: "object", + required: ["data", "integrationId"], } as const; export const $UpdateConnectionLabelsPayloadDto = { - properties: { - labels: { - items: { - type: 'string' - }, - type: 'array' - } + properties: { + labels: { + items: { + type: "string", + }, + type: "array", }, - type: 'object', - required: ['labels'] + }, + type: "object", + required: ["labels"], } as const; export const $InitiateConnectionResponse = { - properties: { - connectionStatus: { - minLength: 1, - type: 'string' - }, - connectedAccountId: { - minLength: 1, - type: 'string' - }, - redirectUrl: { - type: 'string' - } + properties: { + connectionStatus: { + minLength: 1, + type: "string", + }, + connectedAccountId: { + minLength: 1, + type: "string", }, - type: 'object', - required: ['connectionStatus', 'connectedAccountId'] + redirectUrl: { + type: "string", + }, + }, + type: "object", + required: ["connectionStatus", "connectedAccountId"], } as const; export const $ToolsExecuteReqDto = { - properties: { - actionName: { - type: 'string' - }, - runInSandbox: { - type: 'boolean' - }, - input: { - type: 'object' - }, - nlaInput: { - type: 'string' - }, - authorizationData: { - type: 'object' - }, - appSchema: { - type: 'object' - }, - customDescription: { - type: 'string' - }, - systemPrompt: { - type: 'string' - } + properties: { + actionName: { + type: "string", + }, + runInSandbox: { + type: "boolean", + }, + input: { + type: "object", + }, + nlaInput: { + type: "string", }, - type: 'object', - required: ['actionName', 'runInSandbox', 'input'] + authorizationData: { + type: "object", + }, + appSchema: { + type: "object", + }, + customDescription: { + type: "string", + }, + systemPrompt: { + type: "string", + }, + }, + type: "object", + required: ["actionName", "runInSandbox", "input"], } as const; export const $DirectExecuteReqDto = { - properties: { - endpoint: { - type: 'string' - }, - base_url: { - type: 'string' - }, - headers: { - type: 'object' - }, - queryParams: { - type: 'object' - }, - body: { - type: 'object' - } + properties: { + endpoint: { + type: "string", }, - type: 'object', - required: ['endpoint', 'base_url', 'headers', 'queryParams'] + base_url: { + type: "string", + }, + headers: { + type: "object", + }, + queryParams: { + type: "object", + }, + body: { + type: "object", + }, + }, + type: "object", + required: ["endpoint", "base_url", "headers", "queryParams"], } as const; export const $ActionExecutionResDto = { - properties: { - data: { - type: 'object' - }, - error: { - type: 'string' - }, - successfull: { - type: 'string' - } + properties: { + data: { + type: "object", + }, + error: { + type: "string", }, - type: 'object', - required: ['data'] + successfull: { + type: "string", + }, + }, + type: "object", + required: ["data"], } as const; export const $CustomAuthDTO = { - properties: { - base_url: { - type: 'string' - }, - parameters: { - items: { - '$ref': '#/components/schemas/Parameter' - }, - type: 'array' - }, - body: { - type: 'object' - } + properties: { + base_url: { + type: "string", + }, + parameters: { + items: { + $ref: "#/components/schemas/Parameter", + }, + type: "array", }, - type: 'object', - required: ['parameters'] + body: { + type: "object", + }, + }, + type: "object", + required: ["parameters"], } as const; export const $ActionProxyRequestMethodDTO = { - properties: { - type: { - enum: ['formData', 'urlEncoded', 'raw', 'binary', 'graphql', 'none'], - type: 'string', - description: "The type of request body to use for the action. Defaults to 'none'." - }, - data: { - type: 'string', - description: 'The data to be sent to the endpoint. This will override the body set in the connected account.' - } + properties: { + type: { + enum: ["formData", "urlEncoded", "raw", "binary", "graphql", "none"], + type: "string", + description: + "The type of request body to use for the action. Defaults to 'none'.", }, - type: 'object' + data: { + type: "string", + description: + "The data to be sent to the endpoint. This will override the body set in the connected account.", + }, + }, + type: "object", } as const; export const $ActionProxyRequestConfigDTO = { - properties: { - connectedAccountId: { - type: 'string', - description: 'The connected account uuid to use for the action.' - }, - endpoint: { - type: 'string', - description: 'The endpoint to call for the action. If the given url is relative, it will be resolved relative to the base_url set in the connected account info.' - }, - method: { - enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], - type: 'string', - description: 'The HTTP method to use for the action.' - }, - parameters: { - items: { - '$ref': '#/components/schemas/Parameter' - }, - type: 'array' - }, - body: { - type: 'object', - description: 'The body to be sent to the endpoint. This can either be a JSON field or a string.' - } + properties: { + connectedAccountId: { + type: "string", + description: "The connected account uuid to use for the action.", + }, + endpoint: { + type: "string", + description: + "The endpoint to call for the action. If the given url is relative, it will be resolved relative to the base_url set in the connected account info.", + }, + method: { + enum: ["GET", "POST", "PUT", "PATCH", "DELETE"], + type: "string", + description: "The HTTP method to use for the action.", + }, + parameters: { + items: { + $ref: "#/components/schemas/Parameter", + }, + type: "array", + }, + body: { + type: "object", + description: + "The body to be sent to the endpoint. This can either be a JSON field or a string.", }, - type: 'object', - required: ['connectedAccountId', 'endpoint', 'method', 'parameters'] + }, + type: "object", + required: ["connectedAccountId", "endpoint", "method", "parameters"], } as const; export const $SessionInfoDTO = { - properties: { - sessionId: { - type: 'string' - }, - metadata: { - type: 'object' - } + properties: { + sessionId: { + type: "string", + }, + metadata: { + type: "object", }, - type: 'object' + }, + type: "object", } as const; export const $ActionExecutionReqDTO = { - properties: { - connectedAccountId: { - type: 'string' - }, - appName: { - type: 'string' - }, - entityId: { - type: 'string' - }, - endpoint: { - type: 'string' - }, - input: { - type: 'object' - }, - sessionInfo: { - '$ref': '#/components/schemas/SessionInfoDTO' - }, - authConfig: { - '$ref': '#/components/schemas/CustomAuthDTO' - }, - text: { - type: 'string' - }, - customDescription: { - type: 'string' - }, - systemPrompt: { - type: 'string' - } + properties: { + connectedAccountId: { + type: "string", + }, + appName: { + type: "string", + }, + entityId: { + type: "string", + }, + endpoint: { + type: "string", + }, + input: { + type: "object", }, - type: 'object' + sessionInfo: { + $ref: "#/components/schemas/SessionInfoDTO", + }, + authConfig: { + $ref: "#/components/schemas/CustomAuthDTO", + }, + text: { + type: "string", + }, + customDescription: { + type: "string", + }, + systemPrompt: { + type: "string", + }, + }, + type: "object", } as const; export const $ActionGetNLAInputsReqDTO = { - properties: { - text: { - type: 'string' - }, - customDescription: { - type: 'string' - }, - systemPrompt: { - type: 'string' - } + properties: { + text: { + type: "string", + }, + customDescription: { + type: "string", }, - type: 'object', - required: ['text'] + systemPrompt: { + type: "string", + }, + }, + type: "object", + required: ["text"], } as const; export const $ProxyExecutionReqDTO = { - properties: { - endpoint: { - type: 'string' - }, - connectedAccountId: { - type: 'string' - } + properties: { + endpoint: { + type: "string", }, - type: 'object', - required: ['endpoint', 'connectedAccountId'] + connectedAccountId: { + type: "string", + }, + }, + type: "object", + required: ["endpoint", "connectedAccountId"], } as const; export const $ActionDetailsMinimal = { - properties: { - appId: { - type: 'string' - }, - appKey: { - type: 'string' - }, - appName: { - type: 'string' - }, - description: { - type: 'string' - }, - displayName: { - type: 'string' - }, - enabled: { - type: 'boolean' - }, - logo: { - type: 'string' - }, - name: { - type: 'string' - }, - tags: { - items: { - type: 'string' - }, - type: 'array' - }, - deprecated: { - type: 'boolean' - } + properties: { + appId: { + type: "string", + }, + appKey: { + type: "string", + }, + appName: { + type: "string", + }, + description: { + type: "string", }, - type: 'object', - required: ['appKey', 'appName', 'description', 'displayName', 'enabled', 'logo', 'name', 'tags', 'deprecated'] + displayName: { + type: "string", + }, + enabled: { + type: "boolean", + }, + logo: { + type: "string", + }, + name: { + type: "string", + }, + tags: { + items: { + type: "string", + }, + type: "array", + }, + deprecated: { + type: "boolean", + }, + }, + type: "object", + required: [ + "appKey", + "appName", + "description", + "displayName", + "enabled", + "logo", + "name", + "tags", + "deprecated", + ], } as const; export const $ActionDetails = { - properties: { - parameters: { - type: 'object' - }, - response: { - type: 'object' - }, - appId: { - type: 'string' - }, - appKey: { - type: 'string' - }, - appName: { - type: 'string' - }, - description: { - type: 'string' - }, - displayName: { - type: 'string' - }, - enabled: { - type: 'boolean' - }, - logo: { - type: 'string' - }, - name: { - type: 'string' - }, - tags: { - items: { - type: 'string' - }, - type: 'array' - }, - deprecated: { - type: 'boolean' - } + properties: { + parameters: { + type: "object", + }, + response: { + type: "object", + }, + appId: { + type: "string", + }, + appKey: { + type: "string", + }, + appName: { + type: "string", + }, + description: { + type: "string", }, - type: 'object', - required: ['parameters', 'response', 'appKey', 'appName', 'description', 'displayName', 'enabled', 'logo', 'name', 'tags', 'deprecated'] + displayName: { + type: "string", + }, + enabled: { + type: "boolean", + }, + logo: { + type: "string", + }, + name: { + type: "string", + }, + tags: { + items: { + type: "string", + }, + type: "array", + }, + deprecated: { + type: "boolean", + }, + }, + type: "object", + required: [ + "parameters", + "response", + "appKey", + "appName", + "description", + "displayName", + "enabled", + "logo", + "name", + "tags", + "deprecated", + ], } as const; export const $ActionsListResponseDTO = { - properties: { - items: { - items: { - '$ref': '#/components/schemas/ActionDetails' - }, - type: 'array' - }, - page: { - type: 'number' - }, - totalPages: { - type: 'number' - } + properties: { + items: { + items: { + $ref: "#/components/schemas/ActionDetails", + }, + type: "array", }, - type: 'object', - required: ['items', 'page', 'totalPages'] + page: { + type: "number", + }, + totalPages: { + type: "number", + }, + }, + type: "object", + required: ["items", "page", "totalPages"], } as const; export const $ActionsMinimalListResponseDTO = { - properties: { - items: { - items: { - '$ref': '#/components/schemas/ActionDetailsMinimal' - }, - type: 'array' - }, - page: { - type: 'number' - }, - totalPages: { - type: 'number' - } + properties: { + items: { + items: { + $ref: "#/components/schemas/ActionDetailsMinimal", + }, + type: "array", }, - type: 'object', - required: ['items', 'page', 'totalPages'] + page: { + type: "number", + }, + totalPages: { + type: "number", + }, + }, + type: "object", + required: ["items", "page", "totalPages"], } as const; export const $AdvancedUseCaseSearchQueryDTO = { - properties: { - useCase: { - type: 'string' - }, - limit: { - type: 'number' - }, - maxActionsPerTask: { - type: 'number' - }, - minActionsPerTask: { - type: 'number' - }, - apps: { - type: 'string' - } + properties: { + useCase: { + type: "string", + }, + limit: { + type: "number", }, - type: 'object', - required: ['useCase'] + maxActionsPerTask: { + type: "number", + }, + minActionsPerTask: { + type: "number", + }, + apps: { + type: "string", + }, + }, + type: "object", + required: ["useCase"], } as const; export const $AdvancedUseCaseSearchTask = { - properties: { - app: { - type: 'string' - }, - actions: { - items: { - type: 'string' - }, - type: 'array' - }, - description: { - type: 'string' - }, - order: { - type: 'number' - } + properties: { + app: { + type: "string", + }, + actions: { + items: { + type: "string", + }, + type: "array", + }, + description: { + type: "string", }, - type: 'object', - required: ['app', 'actions', 'description', 'order'] + order: { + type: "number", + }, + }, + type: "object", + required: ["app", "actions", "description", "order"], } as const; export const $AdvancedUseCaseSearchResponse = { - properties: { - items: { - items: { - '$ref': '#/components/schemas/AdvancedUseCaseSearchTask' - }, - type: 'array' - } + properties: { + items: { + items: { + $ref: "#/components/schemas/AdvancedUseCaseSearchTask", + }, + type: "array", + }, + }, + type: "object", + required: ["items"], +} as const; + +export const $ExecuteActionResDTO = { + properties: { + response_data: { + type: "boolean", + description: "Indicates if the action was executed successfully", + }, + execution_details: { + type: "object", + description: "Details of the execution status", + }, + }, + type: "object", + required: ["response_data", "execution_details"], +} as const; + +export const $ActionsQueryDTO = { + properties: { + appNames: { + type: "string", + description: "Names of the apps", + }, + useCase: { + type: "string", + description: "Use case", + }, + showEnabledOnly: { + type: "boolean", + description: "Show enabled only", + }, + limit: { + type: "number", + description: "Limit", + }, + apps: { + type: "string", + }, + actions: { + type: "string", + }, + tags: { + type: "string", + }, + usecaseLimit: { + type: "number", + }, + filterImportantActions: { + type: "boolean", }, - type: 'object', - required: ['items'] -} as const; - -export const $ExecuteActionResDTO = { - properties: { - response_data: { - type: 'boolean', - description: 'Indicates if the action was executed successfully' - }, - execution_details: { - type: 'object', - description: 'Details of the execution status' - } + showAll: { + type: "boolean", }, - type: 'object', - required: ['response_data', 'execution_details'] -} as const; - -export const $ActionsQueryDTO = { - properties: { - appNames: { - type: 'string', - description: 'Names of the apps' - }, - useCase: { - type: 'string', - description: 'Use case' - }, - showEnabledOnly: { - type: 'boolean', - description: 'Show enabled only' - }, - limit: { - type: 'number', - description: 'Limit' - }, - apps: { - type: 'string' - }, - actions: { - type: 'string' - }, - tags: { - type: 'string' - }, - usecaseLimit: { - type: 'number' - }, - filterImportantActions: { - type: 'boolean' - }, - showAll: { - type: 'boolean' - }, - page: { - type: 'number' - }, - offset: { - type: 'number' - } + page: { + type: "number", }, - type: 'object' + offset: { + type: "number", + }, + }, + type: "object", } as const; export const $ActionsControllerV1 = { - properties: { - getAction: { - items: { - type: 'object' - }, - type: 'array' - } + properties: { + getAction: { + items: { + type: "object", + }, + type: "array", }, - type: 'object', - required: ['getAction'] + }, + type: "object", + required: ["getAction"], } as const; export const $OAuth2CallbackQueryDto = { - properties: { - state: { - type: 'string' - } + properties: { + state: { + type: "string", }, - type: 'object', - required: ['state'] + }, + type: "object", + required: ["state"], } as const; export const $RedirectUriDTO = { - properties: { - redirectUri: { - type: 'string' - } + properties: { + redirectUri: { + type: "string", }, - type: 'object' + }, + type: "object", } as const; export const $ListTriggersQueryDTO = { - properties: { - appNames: { - type: 'string', - description: 'Names of the apps' - }, - connectedAccountIds: { - type: 'string', - description: 'IDs of the connected accounts' - }, - triggerIds: { - type: 'string', - description: 'IDs of the triggers' - }, - integrationIds: { - type: 'string', - description: 'Integration ID' - }, - showEnabledOnly: { - type: 'boolean', - description: 'Show enabled only' - } + properties: { + appNames: { + type: "string", + description: "Names of the apps", + }, + connectedAccountIds: { + type: "string", + description: "IDs of the connected accounts", }, - type: 'object' + triggerIds: { + type: "string", + description: "IDs of the triggers", + }, + integrationIds: { + type: "string", + description: "Integration ID", + }, + showEnabledOnly: { + type: "boolean", + description: "Show enabled only", + }, + }, + type: "object", } as const; export const $GetActiveTriggersQueryDTO = { - properties: { - connectedAccountIds: { - type: 'string', - description: 'IDs of the connected accounts' - }, - integrationIds: { - type: 'string', - description: 'IDs of the integrations' - }, - triggerIds: { - type: 'string', - description: 'IDs of the triggers' - }, - triggerNames: { - type: 'string', - description: 'Names of the triggers' - }, - page: { - type: 'number', - description: 'Page number' - }, - limit: { - type: 'number', - description: 'Limit per page' - }, - showDisabled: { - type: 'boolean', - description: 'Show disabled triggers' - } + properties: { + connectedAccountIds: { + type: "string", + description: "IDs of the connected accounts", + }, + integrationIds: { + type: "string", + description: "IDs of the integrations", + }, + triggerIds: { + type: "string", + description: "IDs of the triggers", + }, + triggerNames: { + type: "string", + description: "Names of the triggers", }, - type: 'object' + page: { + type: "number", + description: "Page number", + }, + limit: { + type: "number", + description: "Limit per page", + }, + showDisabled: { + type: "boolean", + description: "Show disabled triggers", + }, + }, + type: "object", } as const; export const $GetLogsQueryDTO = { - properties: { - connectionId: { - type: 'string', - description: 'ID of the connection' - }, - integrationId: { - type: 'string', - description: 'ID of the integration' - }, - page: { - type: 'number', - description: 'Page number' - }, - limit: { - type: 'number', - description: 'Limit per page' - } + properties: { + connectionId: { + type: "string", + description: "ID of the connection", + }, + integrationId: { + type: "string", + description: "ID of the integration", + }, + page: { + type: "number", + description: "Page number", }, - type: 'object' + limit: { + type: "number", + description: "Limit per page", + }, + }, + type: "object", } as const; export const $TriggerResDTO = { - properties: { - name: { - type: 'string', - description: 'Trigger name' - }, - display_name: { - type: 'string', - description: 'Trigger display name' - }, - description: { - type: 'string', - description: 'Trigger description' - }, - enabled: { - type: 'boolean', - description: 'Is trigger enabled' - }, - config: { - type: 'object', - description: 'Trigger configuration' - }, - payload: { - type: 'object', - description: 'Trigger payload' - }, - logo: { - type: 'string', - description: 'Trigger logo URL' - }, - count: { - type: 'number', - description: 'Trigger count' - }, - appKey: { - type: 'string', - description: 'App key' - }, - appId: { - type: 'string', - description: 'App ID' - }, - appName: { - type: 'string', - description: 'App name' - }, - instructions: { - type: 'string', - description: 'Trigger instructions' - }, - type: { - type: 'string', - description: 'Trigger type' - } + properties: { + name: { + type: "string", + description: "Trigger name", + }, + display_name: { + type: "string", + description: "Trigger display name", + }, + description: { + type: "string", + description: "Trigger description", + }, + enabled: { + type: "boolean", + description: "Is trigger enabled", + }, + config: { + type: "object", + description: "Trigger configuration", + }, + payload: { + type: "object", + description: "Trigger payload", + }, + logo: { + type: "string", + description: "Trigger logo URL", + }, + count: { + type: "number", + description: "Trigger count", }, - type: 'object', - required: ['name', 'display_name', 'appKey', 'appId', 'appName'] + appKey: { + type: "string", + description: "App key", + }, + appId: { + type: "string", + description: "App ID", + }, + appName: { + type: "string", + description: "App name", + }, + instructions: { + type: "string", + description: "Trigger instructions", + }, + type: { + type: "string", + description: "Trigger type", + }, + }, + type: "object", + required: ["name", "display_name", "appKey", "appId", "appName"], } as const; export const $SingleTriggerResDTO = { - properties: { - name: { - type: 'string', - description: 'Trigger name' - }, - displayName: { - type: 'string', - description: 'Trigger display name' - }, - description: { - type: 'string', - description: 'Trigger description' - }, - type: { - type: 'string', - description: 'Trigger type' - }, - appId: { - type: 'string', - description: 'App ID' - }, - appName: { - type: 'string', - description: 'App name' - }, - instructions: { - type: 'string', - description: 'Trigger instructions' - }, - payload: { - type: 'object', - description: 'Trigger payload' - }, - config: { - type: 'object', - description: 'Trigger config' - } - }, - type: 'object', - required: ['name', 'displayName', 'description', 'type', 'appId', 'appName', 'payload', 'config'] + properties: { + name: { + type: "string", + description: "Trigger name", + }, + displayName: { + type: "string", + description: "Trigger display name", + }, + description: { + type: "string", + description: "Trigger description", + }, + type: { + type: "string", + description: "Trigger type", + }, + appId: { + type: "string", + description: "App ID", + }, + appName: { + type: "string", + description: "App name", + }, + instructions: { + type: "string", + description: "Trigger instructions", + }, + payload: { + type: "object", + description: "Trigger payload", + }, + config: { + type: "object", + description: "Trigger config", + }, + }, + type: "object", + required: [ + "name", + "displayName", + "description", + "type", + "appId", + "appName", + "payload", + "config", + ], } as const; export const $TriggerConfig = { - properties: { - repo: { - type: 'string', - description: 'Repository name' - }, - owner: { - type: 'string', - description: 'Repository owner' - } + properties: { + repo: { + type: "string", + description: "Repository name", + }, + owner: { + type: "string", + description: "Repository owner", }, - type: 'object', - required: ['repo', 'owner'], - description: 'Trigger configuration' + }, + type: "object", + required: ["repo", "owner"], + description: "Trigger configuration", } as const; export const $ActiveTriggerInstance = { - properties: { - id: { - type: 'string', - description: 'Trigger instance ID' - }, - connectionId: { - type: 'string', - description: 'Connected account ID' - }, - triggerName: { - type: 'string', - description: 'Trigger name' - }, - triggerData: { - type: 'string', - description: 'Trigger data' - }, - triggerConfig: { - '$ref': '#/components/schemas/TriggerConfig' - }, - createdAt: { - type: 'string', - description: 'Created at timestamp', - format: 'date-time' - }, - updatedAt: { - type: 'string', - description: 'Updated at timestamp', - format: 'date-time' - }, - disabledAt: { - type: 'string', - description: 'Disabled at timestamp', - format: 'date-time', - nullable: true - } - }, - type: 'object', - required: ['connectionId', 'triggerName', 'triggerConfig', 'createdAt', 'updatedAt'] + properties: { + id: { + type: "string", + description: "Trigger instance ID", + }, + connectionId: { + type: "string", + description: "Connected account ID", + }, + triggerName: { + type: "string", + description: "Trigger name", + }, + triggerData: { + type: "string", + description: "Trigger data", + }, + triggerConfig: { + $ref: "#/components/schemas/TriggerConfig", + }, + createdAt: { + type: "string", + description: "Created at timestamp", + format: "date-time", + }, + updatedAt: { + type: "string", + description: "Updated at timestamp", + format: "date-time", + }, + disabledAt: { + type: "string", + description: "Disabled at timestamp", + format: "date-time", + nullable: true, + }, + }, + type: "object", + required: [ + "connectionId", + "triggerName", + "triggerConfig", + "createdAt", + "updatedAt", + ], } as const; export const $PageInfoDTO = { - properties: { - currentPage: { - type: 'number' - }, - perPage: { - type: 'number' - }, - totalPages: { - type: 'number' - } + properties: { + currentPage: { + type: "number", + }, + perPage: { + type: "number", + }, + totalPages: { + type: "number", }, - type: 'object', - required: ['currentPage', 'perPage', 'totalPages'] + }, + type: "object", + required: ["currentPage", "perPage", "totalPages"], } as const; export const $ActiveTriggersResDTO = { - properties: { - triggers: { - items: { - type: 'object' - }, - type: 'array' - }, - pageInfo: { - items: { - '$ref': '#/components/schemas/PageInfoDTO' - }, - type: 'array' - } + properties: { + triggers: { + items: { + type: "object", + }, + type: "array", + }, + pageInfo: { + items: { + $ref: "#/components/schemas/PageInfoDTO", + }, + type: "array", }, - type: 'object', - required: ['triggers', 'pageInfo'] + }, + type: "object", + required: ["triggers", "pageInfo"], } as const; export const $TriggerLogsResDTO = { - properties: { - data: { - items: { - '$ref': '#/components/schemas/TriggerLogItemDTO' - }, - type: 'array' - }, - pageInfo: { - '$ref': '#/components/schemas/PageInfoDTO' - } + properties: { + data: { + items: { + $ref: "#/components/schemas/TriggerLogItemDTO", + }, + type: "array", + }, + pageInfo: { + $ref: "#/components/schemas/PageInfoDTO", }, - type: 'object', - required: ['data', 'pageInfo'] + }, + type: "object", + required: ["data", "pageInfo"], } as const; export const $TriggerLogItemDTO = { - properties: { - clientId: { - type: 'string', - description: 'Client ID' - }, - connectionId: { - type: 'string', - description: 'Connection ID' - }, - errorTrigger: { - type: 'string', - description: 'Error trigger', - nullable: true - }, - triggerClientError: { - type: 'string', - description: 'Trigger client error', - nullable: true - }, - triggerClientPayload: { - type: 'string', - description: 'Trigger client payload', - nullable: true - }, - triggerProviderPayload: { - type: 'string', - description: 'Trigger provider payload', - nullable: true - }, - triggerName: { - type: 'string', - description: 'Trigger name', - nullable: true - }, - id: { - type: 'string', - description: 'Log ID' - }, - appKey: { - type: 'string', - description: 'App key' - }, - createdAt: { - type: 'string', - description: 'Created at timestamp', - format: 'date-time' - } - }, - type: 'object', - required: ['clientId', 'connectionId', 'id', 'appKey', 'createdAt'] + properties: { + clientId: { + type: "string", + description: "Client ID", + }, + connectionId: { + type: "string", + description: "Connection ID", + }, + errorTrigger: { + type: "string", + description: "Error trigger", + nullable: true, + }, + triggerClientError: { + type: "string", + description: "Trigger client error", + nullable: true, + }, + triggerClientPayload: { + type: "string", + description: "Trigger client payload", + nullable: true, + }, + triggerProviderPayload: { + type: "string", + description: "Trigger provider payload", + nullable: true, + }, + triggerName: { + type: "string", + description: "Trigger name", + nullable: true, + }, + id: { + type: "string", + description: "Log ID", + }, + appKey: { + type: "string", + description: "App key", + }, + createdAt: { + type: "string", + description: "Created at timestamp", + format: "date-time", + }, + }, + type: "object", + required: ["clientId", "connectionId", "id", "appKey", "createdAt"], } as const; export const $HandleTriggerParamsDTO = { - properties: { - appName: { - type: 'string', - description: 'The name of the app' - }, - clientId: { - type: 'string', - description: 'The client ID' - } + properties: { + appName: { + type: "string", + description: "The name of the app", + }, + clientId: { + type: "string", + description: "The client ID", }, - type: 'object', - required: ['appName', 'clientId'] + }, + type: "object", + required: ["appName", "clientId"], } as const; export const $HandleTriggerBodyDTO = { - properties: { - body: { - type: 'object', - description: 'The trigger payload' - } + properties: { + body: { + type: "object", + description: "The trigger payload", }, - type: 'object', - required: ['body'] + }, + type: "object", + required: ["body"], } as const; export const $EnableTriggerParamsDTO = { - properties: { - connectedAccountId: { - type: 'string', - description: 'The connected account ID' - }, - triggerName: { - type: 'string', - description: 'The trigger name' - } + properties: { + connectedAccountId: { + type: "string", + description: "The connected account ID", + }, + triggerName: { + type: "string", + description: "The trigger name", }, - type: 'object', - required: ['connectedAccountId', 'triggerName'] + }, + type: "object", + required: ["connectedAccountId", "triggerName"], } as const; export const $GetTriggerParamsDTO = { - properties: { - triggerId: { - type: 'string', - description: 'The connected account ID' - } + properties: { + triggerId: { + type: "string", + description: "The connected account ID", }, - type: 'object', - required: ['triggerId'] + }, + type: "object", + required: ["triggerId"], } as const; export const $EnableTriggerBodyDTO = { - properties: { - triggerConfig: { - type: 'object', - description: 'The trigger configuration' - }, - verifyHost: { - type: 'string', - description: 'The verify host' - } + properties: { + triggerConfig: { + type: "object", + description: "The trigger configuration", + }, + verifyHost: { + type: "string", + description: "The verify host", }, - type: 'object', - required: ['triggerConfig'] + }, + type: "object", + required: ["triggerConfig"], } as const; export const $SwitchTriggerStatusParamsDTO = { - properties: { - triggerId: { - type: 'string', - description: 'The trigger instance ID' - } + properties: { + triggerId: { + type: "string", + description: "The trigger instance ID", }, - type: 'object', - required: ['triggerId'] + }, + type: "object", + required: ["triggerId"], } as const; export const $SwitchTriggerStatusBodyDTO = { - properties: { - enabled: { - type: 'boolean', - description: 'The new enabled status of the trigger' - } + properties: { + enabled: { + type: "boolean", + description: "The new enabled status of the trigger", }, - type: 'object', - required: ['enabled'] + }, + type: "object", + required: ["enabled"], } as const; export const $TriggerInstanceParamsDTO = { - properties: { - triggerInstanceId: { - type: 'string', - description: 'The trigger instance ID' - } + properties: { + triggerInstanceId: { + type: "string", + description: "The trigger instance ID", }, - type: 'object', - required: ['triggerInstanceId'] + }, + type: "object", + required: ["triggerInstanceId"], } as const; export const $SetCallbackUrlBodyDTO = { - properties: { - callbackURL: { - type: 'string', - description: 'The callback URL' - } + properties: { + callbackURL: { + type: "string", + description: "The callback URL", }, - type: 'object', - required: ['callbackURL'] + }, + type: "object", + required: ["callbackURL"], } as const; export const $TriggerResponseDTO = { - properties: { - status: { - type: 'string', - description: 'The status of the operation' - }, - message: { - type: 'string', - description: 'Optional message' - }, - triggerId: { - type: 'string', - description: 'Optional trigger ID' - }, - isNew: { - type: 'boolean', - description: 'Is new trigger. If true, the trigger was created just now or else it was already existing' - } + properties: { + status: { + type: "string", + description: "The status of the operation", + }, + message: { + type: "string", + description: "Optional message", }, - type: 'object', - required: ['status'] + triggerId: { + type: "string", + description: "Optional trigger ID", + }, + isNew: { + type: "boolean", + description: + "Is new trigger. If true, the trigger was created just now or else it was already existing", + }, + }, + type: "object", + required: ["status"], } as const; export const $WebhookURLResponseDTO = { - properties: { - status: { - type: 'string', - description: 'The status of the operation' - }, - callbackURL: { - type: 'string', - description: 'The callback URL if found' - } + properties: { + status: { + type: "string", + description: "The status of the operation", + }, + callbackURL: { + type: "string", + description: "The callback URL if found", }, - type: 'object', - required: ['status'] + }, + type: "object", + required: ["status"], } as const; export const $TriggerMetadataDTO = { - properties: { - id: { - type: 'string', - description: 'The unique identifier of the trigger' - }, - connectionId: { - type: 'string', - description: 'The connection identifier associated with the trigger' - }, - triggerName: { - type: 'string', - description: 'The name of the trigger' - }, - triggerData: { - type: 'string', - description: 'The data associated with the trigger' - }, - triggerConfig: { - type: 'object', - description: 'The configuration of the trigger' - }, - state: { - type: 'object', - description: 'The state of the trigger' - }, - createdAt: { - type: 'string', - description: 'The creation date of the trigger' - }, - updatedAt: { - type: 'string', - description: 'The last update date of the trigger' - }, - disabledAt: { - type: 'string', - description: 'The date when the trigger was disabled, if applicable' - }, - disabledReason: { - type: 'string', - description: 'The reason why the trigger was disabled, if applicable' - } - }, - type: 'object', - required: ['id', 'connectionId', 'triggerName', 'triggerData', 'triggerConfig', 'state', 'createdAt', 'updatedAt'], - description: 'The trigger details if found' + properties: { + id: { + type: "string", + description: "The unique identifier of the trigger", + }, + connectionId: { + type: "string", + description: "The connection identifier associated with the trigger", + }, + triggerName: { + type: "string", + description: "The name of the trigger", + }, + triggerData: { + type: "string", + description: "The data associated with the trigger", + }, + triggerConfig: { + type: "object", + description: "The configuration of the trigger", + }, + state: { + type: "object", + description: "The state of the trigger", + }, + createdAt: { + type: "string", + description: "The creation date of the trigger", + }, + updatedAt: { + type: "string", + description: "The last update date of the trigger", + }, + disabledAt: { + type: "string", + description: "The date when the trigger was disabled, if applicable", + }, + disabledReason: { + type: "string", + description: "The reason why the trigger was disabled, if applicable", + }, + }, + type: "object", + required: [ + "id", + "connectionId", + "triggerName", + "triggerData", + "triggerConfig", + "state", + "createdAt", + "updatedAt", + ], + description: "The trigger details if found", } as const; export const $GetTriggerResponseDTO = { - properties: { - status: { - type: 'string', - description: 'The status of the operation' - }, - trigger: { - '$ref': '#/components/schemas/TriggerMetadataDTO' - } + properties: { + status: { + type: "string", + description: "The status of the operation", + }, + trigger: { + $ref: "#/components/schemas/TriggerMetadataDTO", }, - type: 'object', - required: ['status'] + }, + type: "object", + required: ["status"], } as const; export const $GenerateCLISessionReqDTO = { - properties: { - channel_name: { - type: 'string', - description: 'The channel name for the CLI session' - } + properties: { + channel_name: { + type: "string", + description: "The channel name for the CLI session", }, - type: 'object', - required: ['channel_name'] + }, + type: "object", + required: ["channel_name"], } as const; export const $GenerateCLISessionResDTO = { - properties: { - key: { - type: 'string', - description: 'The key for the CLI session' - } + properties: { + key: { + type: "string", + description: "The key for the CLI session", }, - type: 'object', - required: ['key'] + }, + type: "object", + required: ["key"], } as const; export const $GetCLISessionResDTO = { - properties: { - clientId: { - type: 'string', - description: 'The client ID' - }, - cliCode: { - type: 'string', - description: 'The CLI code' - } + properties: { + clientId: { + type: "string", + description: "The client ID", + }, + cliCode: { + type: "string", + description: "The CLI code", }, - type: 'object', - required: ['clientId', 'cliCode'] + }, + type: "object", + required: ["clientId", "cliCode"], } as const; export const $VerifyCLICodeResDTO = { - properties: { - clientId: { - type: 'string', - description: 'The client ID' - }, - cliCode: { - type: 'string', - description: 'The CLI code' - }, - apiKey: { - type: 'string', - description: 'The API key associated with the client' - } + properties: { + clientId: { + type: "string", + description: "The client ID", }, - type: 'object', - required: ['clientId', 'cliCode', 'apiKey'] + cliCode: { + type: "string", + description: "The CLI code", + }, + apiKey: { + type: "string", + description: "The API key associated with the client", + }, + }, + type: "object", + required: ["clientId", "cliCode", "apiKey"], } as const; export const $CLIQueryDTO = { - properties: { - key: { - type: 'string', - description: 'Unique key for CLI session' - }, - code: { - type: 'string', - description: 'Code for CLI verification' - } + properties: { + key: { + type: "string", + description: "Unique key for CLI session", + }, + code: { + type: "string", + description: "Code for CLI verification", }, - type: 'object', - required: ['key'] + }, + type: "object", + required: ["key"], } as const; export const $MetadataReqDTO = { - properties: { - email: { - type: 'string', - description: 'The email associated with the metadata request' - }, - metadata: { - description: 'Additional metadata as a key-value pair' - } + properties: { + email: { + type: "string", + description: "The email associated with the metadata request", + }, + metadata: { + description: "Additional metadata as a key-value pair", }, - type: 'object', - required: ['email'] + }, + type: "object", + required: ["email"], } as const; export const $TriggersEnabledToggleReqDTO = { - properties: { - enabled: { - type: 'boolean', - description: 'Flag to enable or disable triggers' - } + properties: { + enabled: { + type: "boolean", + description: "Flag to enable or disable triggers", }, - type: 'object', - required: ['enabled'] + }, + type: "object", + required: ["enabled"], } as const; export const $TriggersEnabledToggleResDTO = { - properties: { - message: { - type: 'string', - description: 'Message indicating the result of the toggle operation' - } + properties: { + message: { + type: "string", + description: "Message indicating the result of the toggle operation", }, - type: 'object', - required: ['message'] + }, + type: "object", + required: ["message"], } as const; export const $TriggerToggleInfoResponseDTO = { - properties: { - triggersEnabled: { - type: 'boolean', - description: 'Indicates if triggers are enabled' - } + properties: { + triggersEnabled: { + type: "boolean", + description: "Indicates if triggers are enabled", }, - type: 'object', - required: ['triggersEnabled'] + }, + type: "object", + required: ["triggersEnabled"], } as const; export const $ToggleTriggerStateResponseDTO = { - properties: { - message: { - type: 'string' - } + properties: { + message: { + type: "string", }, - type: 'object', - required: ['message'] + }, + type: "object", + required: ["message"], } as const; export const $MetadataQueryDTO = { - properties: { - email: { - type: 'string', - description: 'Email of the client' - } + properties: { + email: { + type: "string", + description: "Email of the client", }, - type: 'object', - required: ['email'] + }, + type: "object", + required: ["email"], } as const; export const $TriggerMetadata = { - properties: { - id: { - type: 'string', - description: 'The unique id of the log' - }, - type: { - type: 'string', - description: 'The type of the log', - oneOf: [ - { - type: 'string', - enum: ['trigger'] - } - ] - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The date and time when the log was created', - format: 'date-time' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The date and time when the log was updated', - format: 'date-time' - }, - provider: { - type: 'string', - description: 'The provider of the log' - }, - clientId: { - type: 'string', - description: 'The client uuid of the log' - }, - connectionId: { - type: 'string', - description: 'The connection id of the log' - }, - triggerProviderPayload: { - type: 'string', - description: 'The trigger provider payload of the log' - }, - triggerClientPayload: { - type: 'string' - }, - triggerClientError: { - type: 'string', - description: 'The trigger client error of the log' - }, - triggerName: { - type: 'string', - description: 'The trigger name of the log' - }, - triggerClientResponse: { - type: 'string', - description: 'The trigger client response of the log' - } - }, - type: 'object', - required: ['id', 'type', 'createdAt', 'updatedAt', 'provider', 'clientId', 'connectionId'], - description: 'Metadata associated with the trigger log' + properties: { + id: { + type: "string", + description: "The unique id of the log", + }, + type: { + type: "string", + description: "The type of the log", + oneOf: [ + { + type: "string", + enum: ["trigger"], + }, + ], + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The date and time when the log was created", + format: "date-time", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The date and time when the log was updated", + format: "date-time", + }, + provider: { + type: "string", + description: "The provider of the log", + }, + clientId: { + type: "string", + description: "The client uuid of the log", + }, + connectionId: { + type: "string", + description: "The connection id of the log", + }, + triggerProviderPayload: { + type: "string", + description: "The trigger provider payload of the log", + }, + triggerClientPayload: { + type: "string", + }, + triggerClientError: { + type: "string", + description: "The trigger client error of the log", + }, + triggerName: { + type: "string", + description: "The trigger name of the log", + }, + triggerClientResponse: { + type: "string", + description: "The trigger client response of the log", + }, + }, + type: "object", + required: [ + "id", + "type", + "createdAt", + "updatedAt", + "provider", + "clientId", + "connectionId", + ], + description: "Metadata associated with the trigger log", } as const; export const $ActionMetadata = { - properties: { - id: { - type: 'string', - description: 'The unique id of the log' - }, - request: { - type: 'string', - description: 'The request sent to the provider' - }, - response: { - type: 'string', - description: 'The response from the provider' - }, - errorRequest: { - type: 'string', - description: 'The error request sent to the provider' - }, - type: { - type: 'string', - description: 'The type of the log', - oneOf: [ - { - type: 'string', - enum: ['action'] - } - ] - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The date and time when the log was created', - format: 'date-time' - }, - updatedAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The date and time when the log was updated', - format: 'date-time' - }, - provider: { - type: 'string', - description: 'The provider of the log' - }, - clientId: { - type: 'string', - description: 'The client uuid of the log' - }, - connectionId: { - type: 'string', - description: 'The connection id of the log' - }, - actionName: { - type: 'string', - description: 'The action name of the log' - } - }, - type: 'object', - required: ['id', 'request', 'type', 'createdAt', 'updatedAt', 'provider', 'clientId', 'connectionId', 'actionName'] + properties: { + id: { + type: "string", + description: "The unique id of the log", + }, + request: { + type: "string", + description: "The request sent to the provider", + }, + response: { + type: "string", + description: "The response from the provider", + }, + errorRequest: { + type: "string", + description: "The error request sent to the provider", + }, + type: { + type: "string", + description: "The type of the log", + oneOf: [ + { + type: "string", + enum: ["action"], + }, + ], + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The date and time when the log was created", + format: "date-time", + }, + updatedAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The date and time when the log was updated", + format: "date-time", + }, + provider: { + type: "string", + description: "The provider of the log", + }, + clientId: { + type: "string", + description: "The client uuid of the log", + }, + connectionId: { + type: "string", + description: "The connection id of the log", + }, + actionName: { + type: "string", + description: "The action name of the log", + }, + }, + type: "object", + required: [ + "id", + "request", + "type", + "createdAt", + "updatedAt", + "provider", + "clientId", + "connectionId", + "actionName", + ], } as const; export const $TriggerLogData = { - properties: { - id: { - type: 'string', - description: 'The unique identifier of the trigger log' - }, - connectionId: { - type: 'string', - description: 'The connection identifier associated with the trigger log' - }, - clientId: { - type: 'string', - description: 'The client identifier associated with the trigger log' - }, - status: { - type: 'string', - description: 'The status of the trigger log' - }, - appName: { - type: 'string', - description: 'The name of the application associated with the trigger log' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The creation date and time of the trigger log', - format: 'date-time' - }, - type: { - type: 'string', - description: 'The type of the log', - oneOf: [ - { - type: 'string', - enum: ['trigger'] - } - ] - }, - meta: { - '$ref': '#/components/schemas/TriggerMetadata' - } - }, - type: 'object', - required: ['id', 'connectionId', 'clientId', 'status', 'appName', 'createdAt', 'type', 'meta'] + properties: { + id: { + type: "string", + description: "The unique identifier of the trigger log", + }, + connectionId: { + type: "string", + description: "The connection identifier associated with the trigger log", + }, + clientId: { + type: "string", + description: "The client identifier associated with the trigger log", + }, + status: { + type: "string", + description: "The status of the trigger log", + }, + appName: { + type: "string", + description: + "The name of the application associated with the trigger log", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The creation date and time of the trigger log", + format: "date-time", + }, + type: { + type: "string", + description: "The type of the log", + oneOf: [ + { + type: "string", + enum: ["trigger"], + }, + ], + }, + meta: { + $ref: "#/components/schemas/TriggerMetadata", + }, + }, + type: "object", + required: [ + "id", + "connectionId", + "clientId", + "status", + "appName", + "createdAt", + "type", + "meta", + ], } as const; export const $ActionLogData = { - properties: { - id: { - type: 'string', - description: 'The unique identifier of the action log' - }, - connectionId: { - type: 'string', - description: 'The connection identifier associated with the action log' - }, - clientId: { - type: 'string', - description: 'The client identifier associated with the action log' - }, - status: { - type: 'string', - description: 'The status of the action log' - }, - appName: { - type: 'string', - description: 'The name of the application associated with the action log' - }, - createdAt: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'The creation date and time of the action log', - format: 'date-time' - }, - type: { - type: 'string', - description: 'The type of the log', - oneOf: [ - { - type: 'string', - enum: ['action'] - } - ] - }, - meta: { - '$ref': '#/components/schemas/ActionMetadata' - } - }, - type: 'object', - required: ['id', 'connectionId', 'clientId', 'status', 'appName', 'createdAt', 'type', 'meta'] + properties: { + id: { + type: "string", + description: "The unique identifier of the action log", + }, + connectionId: { + type: "string", + description: "The connection identifier associated with the action log", + }, + clientId: { + type: "string", + description: "The client identifier associated with the action log", + }, + status: { + type: "string", + description: "The status of the action log", + }, + appName: { + type: "string", + description: "The name of the application associated with the action log", + }, + createdAt: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "The creation date and time of the action log", + format: "date-time", + }, + type: { + type: "string", + description: "The type of the log", + oneOf: [ + { + type: "string", + enum: ["action"], + }, + ], + }, + meta: { + $ref: "#/components/schemas/ActionMetadata", + }, + }, + type: "object", + required: [ + "id", + "connectionId", + "clientId", + "status", + "appName", + "createdAt", + "type", + "meta", + ], } as const; export const $LogsResDTO = { - properties: { - nextCursor: { - type: 'string', - description: 'The cursor to get the next page of logs' - }, - data: { - items: { - type: 'object' - }, - type: 'array', - description: 'Logs data' - } + properties: { + nextCursor: { + type: "string", + description: "The cursor to get the next page of logs", }, - type: 'object', - required: ['data'] + data: { + items: { + type: "object", + }, + type: "array", + description: "Logs data", + }, + }, + type: "object", + required: ["data"], } as const; export const $GetLogsDTO = { - properties: { - type: { - enum: ['error', 'info', 'debug'], - type: 'string', - description: 'Type of the log' - }, - time: { - enum: ['5m', '30m', '6h', '1d', '1w', '1month', '1y'], - type: 'string', - description: 'Time interval for which data needs to be fetched' - }, - status: { - enum: ['all', 'success', 'error'], - type: 'string', - description: 'Status of the log' - }, - search: { - type: 'string', - description: 'Search term in the log' - }, - integrationId: { - type: 'string', - description: 'Integration UUID' - }, - entityId: { - type: 'string', - description: 'Entity id' - }, - limit: { - type: 'number', - description: 'Limit of the logs', - default: 10 - }, - cursor: { - type: 'string', - description: 'Cursor for pagination' - }, - logsType: { - type: 'string', - description: 'Type of the log' - }, - sessionId: { - type: 'string', - description: 'Session ID of the log' - } + properties: { + type: { + enum: ["error", "info", "debug"], + type: "string", + description: "Type of the log", }, - type: 'object' + time: { + enum: ["5m", "30m", "6h", "1d", "1w", "1month", "1y"], + type: "string", + description: "Time interval for which data needs to be fetched", + }, + status: { + enum: ["all", "success", "error"], + type: "string", + description: "Status of the log", + }, + search: { + type: "string", + description: "Search term in the log", + }, + integrationId: { + type: "string", + description: "Integration UUID", + }, + entityId: { + type: "string", + description: "Entity id", + }, + limit: { + type: "number", + description: "Limit of the logs", + default: 10, + }, + cursor: { + type: "string", + description: "Cursor for pagination", + }, + logsType: { + type: "string", + description: "Type of the log", + }, + sessionId: { + type: "string", + description: "Session ID of the log", + }, + }, + type: "object", } as const; export const $IngestDataDTO = { - properties: { - connectionId: { - type: 'string', - description: 'Connection ID of the log' - }, - sessionId: { - type: 'string', - description: 'Session ID of the log' - }, - logsType: { - type: 'string', - description: 'Type of the log' - }, - entityId: { - type: 'string', - description: 'Entity ID of the log' - }, - providerName: { - type: 'string', - description: 'Provider name of the log' - }, - actionName: { - type: 'string', - description: 'Action name of the log' - }, - request: { - type: 'object' - }, - response: { - type: 'object' - }, - isError: { - type: 'boolean' - } + properties: { + connectionId: { + type: "string", + description: "Connection ID of the log", + }, + sessionId: { + type: "string", + description: "Session ID of the log", + }, + logsType: { + type: "string", + description: "Type of the log", + }, + entityId: { + type: "string", + description: "Entity ID of the log", + }, + providerName: { + type: "string", + description: "Provider name of the log", + }, + actionName: { + type: "string", + description: "Action name of the log", + }, + request: { + type: "object", + }, + response: { + type: "object", }, - type: 'object', - required: ['providerName', 'actionName', 'request', 'response', 'isError'] + isError: { + type: "boolean", + }, + }, + type: "object", + required: ["providerName", "actionName", "request", "response", "isError"], } as const; export const $IngestDataResponseDTO = { - properties: { - isIngested: { - type: 'boolean' - } + properties: { + isIngested: { + type: "boolean", }, - type: 'object', - required: ['isIngested'] + }, + type: "object", + required: ["isIngested"], } as const; export const $TimePeriodReqDTO = { - properties: { - lastTimePeriod: { - enum: ['DAY', 'WEEK', 'MONTH', 'SIX_MONTH', 'YEAR', 'FIVE_YEAR'], - type: 'string', - description: 'Time period to get the data for' - } + properties: { + lastTimePeriod: { + enum: ["DAY", "WEEK", "MONTH", "SIX_MONTH", "YEAR", "FIVE_YEAR"], + type: "string", + description: "Time period to get the data for", }, - type: 'object' + }, + type: "object", } as const; export const $ActionByAppDTO = { - properties: { - appName: { - type: 'string', - description: 'Name of the app' - }, - totalCount: { - type: 'number', - description: 'Total count of actions for the app' - } + properties: { + appName: { + type: "string", + description: "Name of the app", }, - type: 'object', - required: ['appName', 'totalCount'], - description: 'Action counts by app' + totalCount: { + type: "number", + description: "Total count of actions for the app", + }, + }, + type: "object", + required: ["appName", "totalCount"], + description: "Action counts by app", } as const; export const $ActionByStatusDTO = { - properties: { - failed: { - type: 'number', - description: 'Count of failed actions' - }, - success: { - type: 'number', - description: 'Count of successful actions' - } + properties: { + failed: { + type: "number", + description: "Count of failed actions", }, - type: 'object', - required: ['failed', 'success'], - description: 'Action counts by status' + success: { + type: "number", + description: "Count of successful actions", + }, + }, + type: "object", + required: ["failed", "success"], + description: "Action counts by status", } as const; export const $ActionAnalyticsDTO = { - properties: { - date: { - type: 'string', - description: 'Date of the action', - format: 'date' - }, - byApp: { - '$ref': '#/components/schemas/ActionByAppDTO' - }, - byStatus: { - '$ref': '#/components/schemas/ActionByStatusDTO' - } + properties: { + date: { + type: "string", + description: "Date of the action", + format: "date", + }, + byApp: { + $ref: "#/components/schemas/ActionByAppDTO", }, - type: 'object', - required: ['date', 'byApp', 'byStatus'], - description: 'Comprehensive trigger analytics data, presenting a breakdown by day, status, and provider for all triggers' + byStatus: { + $ref: "#/components/schemas/ActionByStatusDTO", + }, + }, + type: "object", + required: ["date", "byApp", "byStatus"], + description: + "Comprehensive trigger analytics data, presenting a breakdown by day, status, and provider for all triggers", } as const; export const $IntegrationsWithCountsDTO = { - properties: { - id: { - type: 'string', - description: 'Unique identifier for the integration' - }, - appName: { - type: 'string', - description: 'Name of the app' - }, - integrationName: { - type: 'string', - description: 'Name of the integration' - }, - connectionCount: { - type: 'number', - description: 'Count of connections for the integration' - }, - triggerCount: { - type: 'number', - description: 'Count of triggers for the integration' - }, - requestLogsCount: { - type: 'number', - description: 'Count of request logs for the integration' - } - }, - type: 'object', - required: ['id', 'appName', 'integrationName', 'connectionCount', 'triggerCount', 'requestLogsCount'], - description: 'Detailed integration analytics data, including a breakdown of connection count, trigger count, and request logs count for each integration' + properties: { + id: { + type: "string", + description: "Unique identifier for the integration", + }, + appName: { + type: "string", + description: "Name of the app", + }, + integrationName: { + type: "string", + description: "Name of the integration", + }, + connectionCount: { + type: "number", + description: "Count of connections for the integration", + }, + triggerCount: { + type: "number", + description: "Count of triggers for the integration", + }, + requestLogsCount: { + type: "number", + description: "Count of request logs for the integration", + }, + }, + type: "object", + required: [ + "id", + "appName", + "integrationName", + "connectionCount", + "triggerCount", + "requestLogsCount", + ], + description: + "Detailed integration analytics data, including a breakdown of connection count, trigger count, and request logs count for each integration", } as const; export const $AppNameCountDTO = { - properties: { - appName: { - type: 'string', - description: 'Name of the app' - }, - connectionCount: { - type: 'number', - description: 'Count of connections for the app' - }, - triggerCount: { - type: 'number', - description: 'Count of triggers for the app' - }, - requestLogsCount: { - type: 'number', - description: 'Count of request logs for the app' - } + properties: { + appName: { + type: "string", + description: "Name of the app", + }, + connectionCount: { + type: "number", + description: "Count of connections for the app", + }, + triggerCount: { + type: "number", + description: "Count of triggers for the app", }, - type: 'object', - required: ['appName', 'connectionCount', 'triggerCount', 'requestLogsCount'], - description: 'Comprehensive app-level analytics data, providing a breakdown of connection count, trigger count, and request logs count for each app' + requestLogsCount: { + type: "number", + description: "Count of request logs for the app", + }, + }, + type: "object", + required: ["appName", "connectionCount", "triggerCount", "requestLogsCount"], + description: + "Comprehensive app-level analytics data, providing a breakdown of connection count, trigger count, and request logs count for each app", } as const; export const $AnalyticsDataReqDTO = { - properties: { - lastTimePeriod: { - enum: ['DAY', 'WEEK', 'MONTH', 'SIX_MONTH', 'YEAR', 'FIVE_YEAR'], - type: 'string', - description: 'Time period to get the data for' - } + properties: { + lastTimePeriod: { + enum: ["DAY", "WEEK", "MONTH", "SIX_MONTH", "YEAR", "FIVE_YEAR"], + type: "string", + description: "Time period to get the data for", }, - type: 'object' + }, + type: "object", } as const; export const $ClientUniqueUserIdCountDTO = { - properties: { - clientUniqueUserId: { - type: 'string', - description: 'Client unique user id' - }, - count: { - type: 'number', - description: 'Count of connections for the client unique user id' - } + properties: { + clientUniqueUserId: { + type: "string", + description: "Client unique user id", }, - type: 'object', - required: ['clientUniqueUserId', 'count'], - description: 'Connection counts by entity' + count: { + type: "number", + description: "Count of connections for the client unique user id", + }, + }, + type: "object", + required: ["clientUniqueUserId", "count"], + description: "Connection counts by entity", } as const; export const $AnalyticsEntityDataDTO = { - properties: { - byConnections: { - items: { - '$ref': '#/components/schemas/ClientUniqueUserIdCountDTO' - }, - type: 'array' - }, - byActions: { - items: { - '$ref': '#/components/schemas/ClientUniqueUserIdCountDTO' - }, - type: 'array', - description: 'Action counts by entity' - }, - byTriggers: { - items: { - '$ref': '#/components/schemas/ClientUniqueUserIdCountDTO' - }, - type: 'array', - description: 'Trigger counts by entity' - } - }, - type: 'object', - required: ['byConnections', 'byActions', 'byTriggers'], - description: 'Entity-related analytics data, providing a breakdown by connections, actions, and triggers for each entity. This is include all entity info.' + properties: { + byConnections: { + items: { + $ref: "#/components/schemas/ClientUniqueUserIdCountDTO", + }, + type: "array", + }, + byActions: { + items: { + $ref: "#/components/schemas/ClientUniqueUserIdCountDTO", + }, + type: "array", + description: "Action counts by entity", + }, + byTriggers: { + items: { + $ref: "#/components/schemas/ClientUniqueUserIdCountDTO", + }, + type: "array", + description: "Trigger counts by entity", + }, + }, + type: "object", + required: ["byConnections", "byActions", "byTriggers"], + description: + "Entity-related analytics data, providing a breakdown by connections, actions, and triggers for each entity. This is include all entity info.", } as const; export const $AnalyticsDataResDTO = { - properties: { - entity: { - '$ref': '#/components/schemas/AnalyticsEntityDataDTO' - }, - actions: { - items: { - '$ref': '#/components/schemas/ActionAnalyticsDTO' - }, - type: 'array' - }, - trigger: { - items: { - '$ref': '#/components/schemas/ActionAnalyticsDTO' - }, - type: 'array' - }, - integrations: { - items: { - '$ref': '#/components/schemas/IntegrationsWithCountsDTO' - }, - type: 'array' - }, - app: { - '$ref': '#/components/schemas/AppNameCountDTO' - } + properties: { + entity: { + $ref: "#/components/schemas/AnalyticsEntityDataDTO", + }, + actions: { + items: { + $ref: "#/components/schemas/ActionAnalyticsDTO", + }, + type: "array", + }, + trigger: { + items: { + $ref: "#/components/schemas/ActionAnalyticsDTO", + }, + type: "array", }, - type: 'object', - required: ['entity', 'actions', 'trigger', 'integrations', 'app'] + integrations: { + items: { + $ref: "#/components/schemas/IntegrationsWithCountsDTO", + }, + type: "array", + }, + app: { + $ref: "#/components/schemas/AppNameCountDTO", + }, + }, + type: "object", + required: ["entity", "actions", "trigger", "integrations", "app"], } as const; export const $TopEntitiesResDTO = { - properties: { - entities: { - items: { - '$ref': '#/components/schemas/TConnectionCountDTO' - }, - type: 'array', - description: 'Top entities by connection count' - } + properties: { + entities: { + items: { + $ref: "#/components/schemas/TConnectionCountDTO", + }, + type: "array", + description: "Top entities by connection count", }, - type: 'object', - required: ['entities'] + }, + type: "object", + required: ["entities"], } as const; export const $TConnectionCountDTO = { - properties: { - clientUniqueUserId: { - type: 'string', - description: 'Name of the entity' - }, - count: { - type: 'number', - description: 'Count of connections for the entity' - } + properties: { + clientUniqueUserId: { + type: "string", + description: "Name of the entity", + }, + count: { + type: "number", + description: "Count of connections for the entity", }, - type: 'object', - required: ['clientUniqueUserId', 'count'] + }, + type: "object", + required: ["clientUniqueUserId", "count"], } as const; export const $EntityQueryReqDTO = { - properties: { - query: { - type: 'string', - description: 'Query to get the data for' - } + properties: { + query: { + type: "string", + description: "Query to get the data for", }, - type: 'object' + }, + type: "object", } as const; export const $WebhookReqDTO = { - properties: { - eventWebhookURL: { - type: 'string', - description: 'Event Webhook URL' - } + properties: { + eventWebhookURL: { + type: "string", + description: "Event Webhook URL", }, - type: 'object', - required: ['eventWebhookURL'] + }, + type: "object", + required: ["eventWebhookURL"], } as const; export const $FetchQueryDTO = { - properties: { - startTime: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'Start time of the event in ISO 8601 format' - }, - endTime: { - pattern: '\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?', - type: 'string', - description: 'End time of the event in ISO 8601 format' - } + properties: { + startTime: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "Start time of the event in ISO 8601 format", + }, + endTime: { + pattern: "\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d.\\d+Z?", + type: "string", + description: "End time of the event in ISO 8601 format", }, - type: 'object', - required: ['startTime', 'endTime'] + }, + type: "object", + required: ["startTime", "endTime"], } as const; export const $WebhookSecretResDTO = { - properties: { - webhookSecret: { - type: 'string', - description: 'Webhook secret' - } + properties: { + webhookSecret: { + type: "string", + description: "Webhook secret", }, - type: 'object', - required: ['webhookSecret'] + }, + type: "object", + required: ["webhookSecret"], } as const; export const $CreateCheckoutSessionReqDto = { - properties: { - plan: { - enum: ['HOBBY', 'STARTER', 'GROWTH', 'ENTERPRISE', 'STARTUP'], - type: 'string' - } + properties: { + plan: { + enum: ["HOBBY", "STARTER", "GROWTH", "ENTERPRISE", "STARTUP"], + type: "string", }, - type: 'object', - required: ['plan'] + }, + type: "object", + required: ["plan"], } as const; export const $SDKErrorResDTO = { - properties: { - status: { - type: 'string', - description: 'The status of the SDK error' - } - }, - type: 'object', - required: ['status'] -} as const; \ No newline at end of file + properties: { + status: { + type: "string", + description: "The status of the SDK error", + }, + }, + type: "object", + required: ["status"], +} as const; diff --git a/js/src/sdk/client/services.gen.ts b/js/src/sdk/client/services.gen.ts index 2b1b572934..ba563638a3 100644 --- a/js/src/sdk/client/services.gen.ts +++ b/js/src/sdk/client/services.gen.ts @@ -1,617 +1,1088 @@ // This file is auto-generated by @hey-api/openapi-ts -import { createClient, createConfig, type Options } from '@hey-api/client-axios'; -import type { IdentifyClientData, IdentifyClientError, IdentifyClientResponse, GetUserInfoError, GetUserInfoResponse, AddProjectData, AddProjectError, AddProjectResponse, DeleteProjectData, DeleteProjectError, DeleteProjectResponse, GetProjectsError, GetProjectsResponse, GenerateApiKeyData, GenerateApiKeyError, GenerateApiKeyResponse, ListApiKeysError, ListApiKeysResponse, DeleteApiKeyData, DeleteApiKeyError, DeleteApiKeyResponse, GetAppsData, GetAppsError, GetAppsResponse, GetOpenApiSpecsError, GetOpenApiSpecsResponse, DeleteOpenApiSpecToolData, DeleteOpenApiSpecToolError, DeleteOpenApiSpecToolResponse, AppControllerSendEmailToClientData, AppControllerSendEmailToClientError, AppControllerSendEmailToClientResponse, GetOpenApiSpecStatusData, GetOpenApiSpecStatusError, GetOpenApiSpecStatusResponse, GetAppData, GetAppError, GetAppResponse, CreateConnectorData, CreateConnectorError, CreateConnectorResponse, ListAllConnectorsError, ListAllConnectorsResponse, GetConnectorInfoData, GetConnectorInfoError, GetConnectorInfoResponse, ModifyConnectorData, ModifyConnectorError, ModifyConnectorResponse, DeleteConnectorData, DeleteConnectorError, DeleteConnectorResponse, GetConnectionsData, GetConnectionsError, GetConnectionsResponse, InitiateConnectionData, InitiateConnectionError, InitiateConnectionResponse2, UpdateConnectionDataData, UpdateConnectionDataError, UpdateConnectionDataResponse, GetConnectionData, GetConnectionError, GetConnectionResponse, DeleteConnectionData, DeleteConnectionError, DeleteConnectionResponse, GetConnectionInfoData, GetConnectionInfoError, GetConnectionInfoResponse, DisableConnectionData, DisableConnectionError, DisableConnectionResponse, EnableConnectionData, EnableConnectionError, EnableConnectionResponse, ListTriggersData, ListTriggersError, ListTriggersResponse, EnableTriggerData, EnableTriggerError, EnableTriggerResponse, GetActiveTriggersData, GetActiveTriggersError, GetActiveTriggersResponse, SwitchTriggerInstanceStatusData, SwitchTriggerInstanceStatusError, SwitchTriggerInstanceStatusResponse, DisableTriggerData, DisableTriggerError, DisableTriggerResponse, DeleteTriggerData, DeleteTriggerError, DeleteTriggerResponse, SetCallbackUrlData, SetCallbackUrlError, SetCallbackUrlResponse, GetWebhookUrlError, GetWebhookUrlResponse, GetTriggerLogsData, GetTriggerLogsError, GetTriggerLogsResponse, GetTriggerInfoV2Data, GetTriggerInfoV2Error, GetTriggerInfoV2Response, GetSentryDnsError, GetSentryDnsResponse, ClearCacheData, ClearCacheError, ClearCacheResponse, GenerateCliSessionError, GenerateCliSessionResponse, GetCliCodeData, GetCliCodeError, GetCliCodeResponse, VerifyCliCodeData, VerifyCliCodeError, VerifyCliCodeResponse, GetLogsData, GetLogsError, GetLogsResponse, PostLogsData, PostLogsError, PostLogsResponse, ListActionsV2Data, ListActionsV2Error, ListActionsV2Response, ListActionsMinimalV2Data, ListActionsMinimalV2Error, ListActionsMinimalV2Response, ExecuteActionV2Data, ExecuteActionV2Error, ExecuteActionV2Response, GetActionInputsV2Data, GetActionInputsV2Error, GetActionInputsV2Response, GetActionV2Data, GetActionV2Error, GetActionV2Response, ExecuteActionProxyV2Data, ExecuteActionProxyV2Error, ExecuteActionProxyV2Response, AdvancedUseCaseSearchData, AdvancedUseCaseSearchError, AdvancedUseCaseSearchResponse2, GetAnalyticsData, GetAnalyticsError, GetAnalyticsResponse, GetTopEntitiesData, GetTopEntitiesError, GetTopEntitiesResponse, UpdateWebhookData, UpdateWebhookError, UpdateWebhookResponse } from './types.gen'; +import { + createClient, + createConfig, + type Options, +} from "@hey-api/client-axios"; +import type { + IdentifyClientData, + IdentifyClientError, + IdentifyClientResponse, + GetUserInfoError, + GetUserInfoResponse, + AddProjectData, + AddProjectError, + AddProjectResponse, + DeleteProjectData, + DeleteProjectError, + DeleteProjectResponse, + GetProjectsError, + GetProjectsResponse, + GenerateApiKeyData, + GenerateApiKeyError, + GenerateApiKeyResponse, + ListApiKeysError, + ListApiKeysResponse, + DeleteApiKeyData, + DeleteApiKeyError, + DeleteApiKeyResponse, + GetAppsData, + GetAppsError, + GetAppsResponse, + GetOpenApiSpecsError, + GetOpenApiSpecsResponse, + DeleteOpenApiSpecToolData, + DeleteOpenApiSpecToolError, + DeleteOpenApiSpecToolResponse, + AppControllerSendEmailToClientData, + AppControllerSendEmailToClientError, + AppControllerSendEmailToClientResponse, + GetOpenApiSpecStatusData, + GetOpenApiSpecStatusError, + GetOpenApiSpecStatusResponse, + GetAppData, + GetAppError, + GetAppResponse, + CreateConnectorData, + CreateConnectorError, + CreateConnectorResponse, + ListAllConnectorsError, + ListAllConnectorsResponse, + GetConnectorInfoData, + GetConnectorInfoError, + GetConnectorInfoResponse, + ModifyConnectorData, + ModifyConnectorError, + ModifyConnectorResponse, + DeleteConnectorData, + DeleteConnectorError, + DeleteConnectorResponse, + GetConnectionsData, + GetConnectionsError, + GetConnectionsResponse, + InitiateConnectionData, + InitiateConnectionError, + InitiateConnectionResponse2, + UpdateConnectionDataData, + UpdateConnectionDataError, + UpdateConnectionDataResponse, + GetConnectionData, + GetConnectionError, + GetConnectionResponse, + DeleteConnectionData, + DeleteConnectionError, + DeleteConnectionResponse, + GetConnectionInfoData, + GetConnectionInfoError, + GetConnectionInfoResponse, + DisableConnectionData, + DisableConnectionError, + DisableConnectionResponse, + EnableConnectionData, + EnableConnectionError, + EnableConnectionResponse, + ListTriggersData, + ListTriggersError, + ListTriggersResponse, + EnableTriggerData, + EnableTriggerError, + EnableTriggerResponse, + GetActiveTriggersData, + GetActiveTriggersError, + GetActiveTriggersResponse, + SwitchTriggerInstanceStatusData, + SwitchTriggerInstanceStatusError, + SwitchTriggerInstanceStatusResponse, + DisableTriggerData, + DisableTriggerError, + DisableTriggerResponse, + DeleteTriggerData, + DeleteTriggerError, + DeleteTriggerResponse, + SetCallbackUrlData, + SetCallbackUrlError, + SetCallbackUrlResponse, + GetWebhookUrlError, + GetWebhookUrlResponse, + GetTriggerLogsData, + GetTriggerLogsError, + GetTriggerLogsResponse, + GetTriggerInfoV2Data, + GetTriggerInfoV2Error, + GetTriggerInfoV2Response, + GetSentryDnsError, + GetSentryDnsResponse, + ClearCacheData, + ClearCacheError, + ClearCacheResponse, + GenerateCliSessionError, + GenerateCliSessionResponse, + GetCliCodeData, + GetCliCodeError, + GetCliCodeResponse, + VerifyCliCodeData, + VerifyCliCodeError, + VerifyCliCodeResponse, + GetLogsData, + GetLogsError, + GetLogsResponse, + PostLogsData, + PostLogsError, + PostLogsResponse, + ListActionsV2Data, + ListActionsV2Error, + ListActionsV2Response, + ListActionsMinimalV2Data, + ListActionsMinimalV2Error, + ListActionsMinimalV2Response, + ExecuteActionV2Data, + ExecuteActionV2Error, + ExecuteActionV2Response, + GetActionInputsV2Data, + GetActionInputsV2Error, + GetActionInputsV2Response, + GetActionV2Data, + GetActionV2Error, + GetActionV2Response, + ExecuteActionProxyV2Data, + ExecuteActionProxyV2Error, + ExecuteActionProxyV2Response, + AdvancedUseCaseSearchData, + AdvancedUseCaseSearchError, + AdvancedUseCaseSearchResponse2, + GetAnalyticsData, + GetAnalyticsError, + GetAnalyticsResponse, + GetTopEntitiesData, + GetTopEntitiesError, + GetTopEntitiesResponse, + UpdateWebhookData, + UpdateWebhookError, + UpdateWebhookResponse, +} from "./types.gen"; export const client = createClient(createConfig()); export class AuthService { - /** - * Identify client - */ - public static identifyClient(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/client/auth/identify' - }); - } - - /** - * Get user info - * Get client info - */ - public static getUserInfo(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/client/auth/client_info' - }); - } - - /** - * Add project - */ - public static addProject(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/client/auth/project/add' - }); - } - - /** - * Delete project - */ - public static deleteProject(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/client/auth/project/delete/{projectId}' - }); - } - - /** - * Get projects - */ - public static getProjects(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/client/auth/projects' - }); - } - + /** + * Identify client + */ + public static identifyClient( + options?: Options + ) { + return (options?.client ?? client).post< + IdentifyClientResponse, + IdentifyClientError, + ThrowOnError + >({ + ...options, + url: "/api/v1/client/auth/identify", + }); + } + + /** + * Get user info + * Get client info + */ + public static getUserInfo( + options?: Options + ) { + return (options?.client ?? client).get< + GetUserInfoResponse, + GetUserInfoError, + ThrowOnError + >({ + ...options, + url: "/api/v1/client/auth/client_info", + }); + } + + /** + * Add project + */ + public static addProject( + options?: Options + ) { + return (options?.client ?? client).post< + AddProjectResponse, + AddProjectError, + ThrowOnError + >({ + ...options, + url: "/api/v1/client/auth/project/add", + }); + } + + /** + * Delete project + */ + public static deleteProject( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteProjectResponse, + DeleteProjectError, + ThrowOnError + >({ + ...options, + url: "/api/v1/client/auth/project/delete/{projectId}", + }); + } + + /** + * Get projects + */ + public static getProjects( + options?: Options + ) { + return (options?.client ?? client).get< + GetProjectsResponse, + GetProjectsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/client/auth/projects", + }); + } } export class ApiKeysService { - /** - * Generate api key - */ - public static generateApiKey(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/api_keys' - }); - } - - /** - * List api keys - */ - public static listApiKeys(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/api_keys' - }); - } - - /** - * Delete api key - */ - public static deleteApiKey(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/api_keys/{id}' - }); - } - + /** + * Generate api key + */ + public static generateApiKey( + options: Options + ) { + return (options?.client ?? client).post< + GenerateApiKeyResponse, + GenerateApiKeyError, + ThrowOnError + >({ + ...options, + url: "/api/v1/api_keys", + }); + } + + /** + * List api keys + */ + public static listApiKeys( + options?: Options + ) { + return (options?.client ?? client).get< + ListApiKeysResponse, + ListApiKeysError, + ThrowOnError + >({ + ...options, + url: "/api/v1/api_keys", + }); + } + + /** + * Delete api key + */ + public static deleteApiKey( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteApiKeyResponse, + DeleteApiKeyError, + ThrowOnError + >({ + ...options, + url: "/api/v1/api_keys/{id}", + }); + } } export class AppsService { - /** - * Get apps - * Retrieve a list of all applications based on query parameters. - */ - public static getApps(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/apps' - }); - } - - /** - * Get opena api specs - * List all openapi spec tools - */ - public static getOpenApiSpecs(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/apps/openapi/spec/list' - }); - } - - /** - * Delete open api spec tool - * Delete an openapi spec tool - */ - public static deleteOpenApiSpecTool(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/apps/openapi/spec/delete/{id}' - }); - } - - /** - * Send email to client - */ - public static sendEmailToClient(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/apps/openapi/send_email_to_client' - }); - } - - /** - * Get open api spec status - * Get the status of an openapi spec tool - */ - public static getOpenApiSpecStatus(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/apps/openapi/spec/status/{id}' - }); - } - - /** - * Get app - * Get app details - */ - public static getApp(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/apps/{appName}' - }); - } - + /** + * Get apps + * Retrieve a list of all applications based on query parameters. + */ + public static getApps( + options?: Options + ) { + return (options?.client ?? client).get< + GetAppsResponse, + GetAppsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps", + }); + } + + /** + * Get opena api specs + * List all openapi spec tools + */ + public static getOpenApiSpecs( + options?: Options + ) { + return (options?.client ?? client).get< + GetOpenApiSpecsResponse, + GetOpenApiSpecsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps/openapi/spec/list", + }); + } + + /** + * Delete open api spec tool + * Delete an openapi spec tool + */ + public static deleteOpenApiSpecTool( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteOpenApiSpecToolResponse, + DeleteOpenApiSpecToolError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps/openapi/spec/delete/{id}", + }); + } + + /** + * Send email to client + */ + public static sendEmailToClient( + options?: Options + ) { + return (options?.client ?? client).post< + AppControllerSendEmailToClientResponse, + AppControllerSendEmailToClientError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps/openapi/send_email_to_client", + }); + } + + /** + * Get open api spec status + * Get the status of an openapi spec tool + */ + public static getOpenApiSpecStatus( + options: Options + ) { + return (options?.client ?? client).get< + GetOpenApiSpecStatusResponse, + GetOpenApiSpecStatusError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps/openapi/spec/status/{id}", + }); + } + + /** + * Get app + * Get app details + */ + public static getApp( + options: Options + ) { + return (options?.client ?? client).get< + GetAppResponse, + GetAppError, + ThrowOnError + >({ + ...options, + url: "/api/v1/apps/{appName}", + }); + } } export class IntegrationsService { - /** - * Create connector - * Create a new connector - */ - public static createConnector(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/integrations' - }); - } - - /** - * List all connectors - * List all connectors - */ - public static listAllConnectors(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/integrations' - }); - } - - /** - * Get connector info - * Get connector info - */ - public static getConnectorInfo(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/integrations/{integrationId}' - }); - } - - /** - * Modify connector - * Modify a connector - */ - public static modifyConnector(options: Options) { - return (options?.client ?? client).patch({ - ...options, - url: '/api/v1/integrations/{integrationId}' - }); - } - - /** - * Delete connector - * Delete a connector - */ - public static deleteConnector(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/integrations/{integrationId}' - }); - } - + /** + * Create connector + * Create a new connector + */ + public static createConnector( + options?: Options + ) { + return (options?.client ?? client).post< + CreateConnectorResponse, + CreateConnectorError, + ThrowOnError + >({ + ...options, + url: "/api/v1/integrations", + }); + } + + /** + * List all connectors + * List all connectors + */ + public static listAllConnectors( + options?: Options + ) { + return (options?.client ?? client).get< + ListAllConnectorsResponse, + ListAllConnectorsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/integrations", + }); + } + + /** + * Get connector info + * Get connector info + */ + public static getConnectorInfo( + options: Options + ) { + return (options?.client ?? client).get< + GetConnectorInfoResponse, + GetConnectorInfoError, + ThrowOnError + >({ + ...options, + url: "/api/v1/integrations/{integrationId}", + }); + } + + /** + * Modify connector + * Modify a connector + */ + public static modifyConnector( + options: Options + ) { + return (options?.client ?? client).patch< + ModifyConnectorResponse, + ModifyConnectorError, + ThrowOnError + >({ + ...options, + url: "/api/v1/integrations/{integrationId}", + }); + } + + /** + * Delete connector + * Delete a connector + */ + public static deleteConnector( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteConnectorResponse, + DeleteConnectorError, + ThrowOnError + >({ + ...options, + url: "/api/v1/integrations/{integrationId}", + }); + } } export class ConnectionsService { - /** - * Get connections - */ - public static getConnections(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/connectedAccounts' - }); - } - - /** - * Initiate connection - */ - public static initiateConnection(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/connectedAccounts' - }); - } - - /** - * Update connection data - * Update connection data - */ - public static updateConnectionData(options: Options) { - return (options?.client ?? client).patch({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}/data' - }); - } - - /** - * Get connection - */ - public static getConnection(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}' - }); - } - - /** - * Delete connection - * Delete a connection - */ - public static deleteConnection(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}' - }); - } - - /** - * Get connection info - * Get connection info - */ - public static getConnectionInfo(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}/info' - }); - } - - /** - * Disable connection - * Disable a connection - */ - public static disableConnection(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}/disable' - }); - } - - /** - * Enable connection - * Enable a connection - */ - public static enableConnection(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/connectedAccounts/{connectedAccountId}/enable' - }); - } - + /** + * Get connections + */ + public static getConnections( + options?: Options + ) { + return (options?.client ?? client).get< + GetConnectionsResponse, + GetConnectionsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts", + }); + } + + /** + * Initiate connection + */ + public static initiateConnection( + options?: Options + ) { + return (options?.client ?? client).post< + InitiateConnectionResponse2, + InitiateConnectionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts", + }); + } + + /** + * Update connection data + * Update connection data + */ + public static updateConnectionData( + options: Options + ) { + return (options?.client ?? client).patch< + UpdateConnectionDataResponse, + UpdateConnectionDataError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}/data", + }); + } + + /** + * Get connection + */ + public static getConnection( + options: Options + ) { + return (options?.client ?? client).get< + GetConnectionResponse, + GetConnectionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}", + }); + } + + /** + * Delete connection + * Delete a connection + */ + public static deleteConnection( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteConnectionResponse, + DeleteConnectionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}", + }); + } + + /** + * Get connection info + * Get connection info + */ + public static getConnectionInfo( + options: Options + ) { + return (options?.client ?? client).get< + GetConnectionInfoResponse, + GetConnectionInfoError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}/info", + }); + } + + /** + * Disable connection + * Disable a connection + */ + public static disableConnection( + options: Options + ) { + return (options?.client ?? client).post< + DisableConnectionResponse, + DisableConnectionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}/disable", + }); + } + + /** + * Enable connection + * Enable a connection + */ + public static enableConnection( + options: Options + ) { + return (options?.client ?? client).post< + EnableConnectionResponse, + EnableConnectionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/connectedAccounts/{connectedAccountId}/enable", + }); + } } export class TriggersService { - /** - * List triggers - * List triggers - */ - public static listTriggers(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/triggers' - }); - } - - /** - * Enable trigger - * Enables a trigger for a connected account and specific trigger name. - */ - public static enableTrigger(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/triggers/enable/{connectedAccountId}/{triggerName}' - }); - } - - /** - * Get active triggers - * Lists active triggers based on query parameters. - */ - public static getActiveTriggers(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/triggers/active_triggers' - }); - } - - /** - * Switch trigger instance status - * Switches the status of a trigger instance. - */ - public static switchTriggerInstanceStatus(options: Options) { - return (options?.client ?? client).patch({ - ...options, - url: '/api/v1/triggers/instance/{triggerId}/status' - }); - } - - /** - * Disable trigger - * Disables a specified trigger instance. - */ - public static disableTrigger(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/triggers/disable/{triggerInstanceId}' - }); - } - - /** - * Delete trigger - * Deletes a specified trigger instance. - */ - public static deleteTrigger(options: Options) { - return (options?.client ?? client).delete({ - ...options, - url: '/api/v1/triggers/instance/{triggerInstanceId}' - }); - } - - /** - * Set callback url - * Sets a universal callback URL for the client. - */ - public static setCallbackUrl(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/triggers/set_callback_url' - }); - } - - /** - * Get webhook url - * Retrieves the universal callback URL set for the client. - */ - public static getWebhookUrl(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/triggers/callback_url' - }); - } - - /** - * Get logs - * Fetches logs based on connection and integration details. - */ - public static getTriggerLogs(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/triggers/logs' - }); - } - - /** - * Get trigger info - * Get Trigger Info - */ - public static getTriggerInfoV2(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v2/triggers/{triggerName}' - }); - } - + /** + * List triggers + * List triggers + */ + public static listTriggers( + options?: Options + ) { + return (options?.client ?? client).get< + ListTriggersResponse, + ListTriggersError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers", + }); + } + + /** + * Enable trigger + * Enables a trigger for a connected account and specific trigger name. + */ + public static enableTrigger( + options: Options + ) { + return (options?.client ?? client).post< + EnableTriggerResponse, + EnableTriggerError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/enable/{connectedAccountId}/{triggerName}", + }); + } + + /** + * Get active triggers + * Lists active triggers based on query parameters. + */ + public static getActiveTriggers( + options?: Options + ) { + return (options?.client ?? client).get< + GetActiveTriggersResponse, + GetActiveTriggersError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/active_triggers", + }); + } + + /** + * Switch trigger instance status + * Switches the status of a trigger instance. + */ + public static switchTriggerInstanceStatus< + ThrowOnError extends boolean = false, + >(options: Options) { + return (options?.client ?? client).patch< + SwitchTriggerInstanceStatusResponse, + SwitchTriggerInstanceStatusError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/instance/{triggerId}/status", + }); + } + + /** + * Disable trigger + * Disables a specified trigger instance. + */ + public static disableTrigger( + options: Options + ) { + return (options?.client ?? client).post< + DisableTriggerResponse, + DisableTriggerError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/disable/{triggerInstanceId}", + }); + } + + /** + * Delete trigger + * Deletes a specified trigger instance. + */ + public static deleteTrigger( + options: Options + ) { + return (options?.client ?? client).delete< + DeleteTriggerResponse, + DeleteTriggerError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/instance/{triggerInstanceId}", + }); + } + + /** + * Set callback url + * Sets a universal callback URL for the client. + */ + public static setCallbackUrl( + options?: Options + ) { + return (options?.client ?? client).post< + SetCallbackUrlResponse, + SetCallbackUrlError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/set_callback_url", + }); + } + + /** + * Get webhook url + * Retrieves the universal callback URL set for the client. + */ + public static getWebhookUrl( + options?: Options + ) { + return (options?.client ?? client).get< + GetWebhookUrlResponse, + GetWebhookUrlError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/callback_url", + }); + } + + /** + * Get logs + * Fetches logs based on connection and integration details. + */ + public static getTriggerLogs( + options?: Options + ) { + return (options?.client ?? client).get< + GetTriggerLogsResponse, + GetTriggerLogsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/triggers/logs", + }); + } + + /** + * Get trigger info + * Get Trigger Info + */ + public static getTriggerInfoV2( + options: Options + ) { + return (options?.client ?? client).get< + GetTriggerInfoV2Response, + GetTriggerInfoV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/triggers/{triggerName}", + }); + } } export class AdminService { - /** - * Jssentry dns - */ - public static getSentryDns(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/cli/js-sentry-dns' - }); - } - - /** - * Clear cache - */ - public static clearCache(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/clear-cache' - }); - } - + /** + * Jssentry dns + */ + public static getSentryDns( + options?: Options + ) { + return (options?.client ?? client).get< + GetSentryDnsResponse, + GetSentryDnsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/cli/js-sentry-dns", + }); + } + + /** + * Clear cache + */ + public static clearCache( + options?: Options + ) { + return (options?.client ?? client).post< + ClearCacheResponse, + ClearCacheError, + ThrowOnError + >({ + ...options, + url: "/api/v1/clear-cache", + }); + } } export class CliService { - /** - * Handle cli code exchange - */ - public static generateCliSession(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/cli/generate-cli-session' - }); - } - - /** - * Get cli code - */ - public static getCliCode(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/cli/get-cli-code' - }); - } - - /** - * Handle cli code verification - */ - public static verifyCliCode(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/cli/verify-cli-code' - }); - } - + /** + * Handle cli code exchange + */ + public static generateCliSession( + options?: Options + ) { + return (options?.client ?? client).get< + GenerateCliSessionResponse, + GenerateCliSessionError, + ThrowOnError + >({ + ...options, + url: "/api/v1/cli/generate-cli-session", + }); + } + + /** + * Get cli code + */ + public static getCliCode( + options: Options + ) { + return (options?.client ?? client).get< + GetCliCodeResponse, + GetCliCodeError, + ThrowOnError + >({ + ...options, + url: "/api/v1/cli/get-cli-code", + }); + } + + /** + * Handle cli code verification + */ + public static verifyCliCode( + options: Options + ) { + return (options?.client ?? client).get< + VerifyCliCodeResponse, + VerifyCliCodeError, + ThrowOnError + >({ + ...options, + url: "/api/v1/cli/verify-cli-code", + }); + } } export class LogsService { - /** - * Get logs - * List logs - */ - public static getLogs(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/logs/' - }); - } - - /** - * Post logs - * Add new logs - */ - public static postLogs(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/logs/' - }); - } - + /** + * Get logs + * List logs + */ + public static getLogs( + options?: Options + ) { + return (options?.client ?? client).get< + GetLogsResponse, + GetLogsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/logs/", + }); + } + + /** + * Post logs + * Add new logs + */ + public static postLogs( + options?: Options + ) { + return (options?.client ?? client).post< + PostLogsResponse, + PostLogsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/logs/", + }); + } } export class ActionsService { - /** - * List actions - * Retrieve a list of all actions based on query parameters. - */ - public static listActionsV2(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v2/actions' - }); - } - - /** - * List actions minimal - * Retrieve a list of all actions based on query parameters. - */ - public static listActionsMinimalV2(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v2/actions/list/all' - }); - } - - /** - * Execute action - * Execute an action. Support both connected account and no auth auth. - */ - public static executeActionV2(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v2/actions/{actionId}/execute' - }); - } - - /** - * Get action inputs - * Get the inputs for an action with NLA - */ - public static getActionInputsV2(options: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v2/actions/{actionId}/execute/get.inputs' - }); - } - - /** - * Get action - * Get action details - */ - public static getActionV2(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v2/actions/{actionId}' - }); - } - - /** - * Execute action proxy - * Execute an action with direct auth. - */ - public static executeActionProxyV2(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v2/actions/proxy' - }); - } - - /** - * Advanced use case search - * Perform use case search. - */ - public static advancedUseCaseSearch(options: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v2/actions/search/advanced' - }); - } - + /** + * List actions + * Retrieve a list of all actions based on query parameters. + */ + public static listActionsV2( + options?: Options + ) { + return (options?.client ?? client).get< + ListActionsV2Response, + ListActionsV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions", + }); + } + + /** + * List actions minimal + * Retrieve a list of all actions based on query parameters. + */ + public static listActionsMinimalV2( + options?: Options + ) { + return (options?.client ?? client).get< + ListActionsMinimalV2Response, + ListActionsMinimalV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/list/all", + }); + } + + /** + * Execute action + * Execute an action. Support both connected account and no auth auth. + */ + public static executeActionV2( + options: Options + ) { + return (options?.client ?? client).post< + ExecuteActionV2Response, + ExecuteActionV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/{actionId}/execute", + }); + } + + /** + * Get action inputs + * Get the inputs for an action with NLA + */ + public static getActionInputsV2( + options: Options + ) { + return (options?.client ?? client).post< + GetActionInputsV2Response, + GetActionInputsV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/{actionId}/execute/get.inputs", + }); + } + + /** + * Get action + * Get action details + */ + public static getActionV2( + options: Options + ) { + return (options?.client ?? client).get< + GetActionV2Response, + GetActionV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/{actionId}", + }); + } + + /** + * Execute action proxy + * Execute an action with direct auth. + */ + public static executeActionProxyV2( + options?: Options + ) { + return (options?.client ?? client).post< + ExecuteActionProxyV2Response, + ExecuteActionProxyV2Error, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/proxy", + }); + } + + /** + * Advanced use case search + * Perform use case search. + */ + public static advancedUseCaseSearch( + options: Options + ) { + return (options?.client ?? client).get< + AdvancedUseCaseSearchResponse2, + AdvancedUseCaseSearchError, + ThrowOnError + >({ + ...options, + url: "/api/v2/actions/search/advanced", + }); + } } export class AnalyticsService { - /** - * Get analytics - */ - public static getAnalytics(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/analytics/' - }); - } - - /** - * Get top entities - */ - public static getTopEntities(options?: Options) { - return (options?.client ?? client).get({ - ...options, - url: '/api/v1/analytics/entities' - }); - } - + /** + * Get analytics + */ + public static getAnalytics( + options?: Options + ) { + return (options?.client ?? client).get< + GetAnalyticsResponse, + GetAnalyticsError, + ThrowOnError + >({ + ...options, + url: "/api/v1/analytics/", + }); + } + + /** + * Get top entities + */ + public static getTopEntities( + options?: Options + ) { + return (options?.client ?? client).get< + GetTopEntitiesResponse, + GetTopEntitiesError, + ThrowOnError + >({ + ...options, + url: "/api/v1/analytics/entities", + }); + } } export class EventLogsService { - /** - * Update webhook - */ - public static updateWebhook(options?: Options) { - return (options?.client ?? client).post({ - ...options, - url: '/api/v1/event_logs/set/webhook' - }); - } - -} \ No newline at end of file + /** + * Update webhook + */ + public static updateWebhook( + options?: Options + ) { + return (options?.client ?? client).post< + UpdateWebhookResponse, + UpdateWebhookError, + ThrowOnError + >({ + ...options, + url: "/api/v1/event_logs/set/webhook", + }); + } +} diff --git a/js/src/sdk/client/types.gen.ts b/js/src/sdk/client/types.gen.ts index 6bdd0f2e06..2852a47df5 100644 --- a/js/src/sdk/client/types.gen.ts +++ b/js/src/sdk/client/types.gen.ts @@ -4,2277 +4,2327 @@ * Member information */ export type MemberInfoResDTO = { - id: string; - projectId: string; - email: string; - name: string; - role: string; - metadata?: unknown; - createdAt: string; - updatedAt: string; - deletedAt?: string; + id: string; + projectId: string; + email: string; + name: string; + role: string; + metadata?: unknown; + createdAt: string; + updatedAt: string; + deletedAt?: string; }; export type MagicLinkResDTO = { - status: string; + status: string; }; export type MagicLinkReqDTO = { - /** - * The email of the user - */ - email: string; - /** - * The frontend host of the user - */ - verifyHost: string; + /** + * The email of the user + */ + email: string; + /** + * The frontend host of the user + */ + verifyHost: string; }; export type LogoutResDTO = { - /** - * Message confirming the logout - */ - message: string; + /** + * Message confirming the logout + */ + message: string; }; export type VerifyMagicLinkReqDTO = { - /** - * The magic link token - */ - token: string; + /** + * The magic link token + */ + token: string; }; /** * Data containing client and token information if verification is successful */ export type VerifyMagicLinkDataDTO = { - clientId: string; - isValid: boolean; - jwtToken: string; - email: string; + clientId: string; + isValid: boolean; + jwtToken: string; + email: string; }; export type VerifyMagicLinkResDTO = { - /** - * Message indicating the result of the verification - */ - message: string; - data?: VerifyMagicLinkDataDTO; + /** + * Message indicating the result of the verification + */ + message: string; + data?: VerifyMagicLinkDataDTO; }; export type IdentifyClientReqDTO = { - /** - * The hash of the client - */ - hash: string; - /** - * The framework used by the client - */ - framework?: string; + /** + * The hash of the client + */ + hash: string; + /** + * The framework used by the client + */ + framework?: string; }; export type IdentifyClientResDTO = { - /** - * The client ID - */ - clientId: string; - /** - * The API key associated with the client - */ - apiKey: string; - /** - * The email associated with the client - */ - email: string; - /** - * The organization ID associated with the client - */ - orgId: string; + /** + * The client ID + */ + clientId: string; + /** + * The API key associated with the client + */ + apiKey: string; + /** + * The email associated with the client + */ + email: string; + /** + * The organization ID associated with the client + */ + orgId: string; }; /** * User Git information */ export type UserGitUserInfo = { - name?: string; - email: string; + name?: string; + email: string; }; export type TrackClientReqDTO = { - /** - * The framework used by the client - */ - framework: string; - /** - * The MAC address of the client device - */ - mac_address?: string; - user_git_user_info?: UserGitUserInfo; + /** + * The framework used by the client + */ + framework: string; + /** + * The MAC address of the client device + */ + mac_address?: string; + user_git_user_info?: UserGitUserInfo; }; export type TrackClientResDTO = { - /** - * Message indicating the result of the tracking operation - */ - message: string; + /** + * Message indicating the result of the tracking operation + */ + message: string; }; export type DeleteRowAPIDTO = { - /** - * Status of the delete operation - */ - status: string; - /** - * Number of records deleted - */ - count: number; + /** + * Status of the delete operation + */ + status: string; + /** + * Number of records deleted + */ + count: number; }; /** * Client information */ export type ClientDTO = { - /** - * Auto-generated ID of the client - */ - autoId: number; - /** - * Unique ID of the client - */ - id: string; - /** - * Name of the client - */ - name: string; - /** - * Email of the client - */ - email: string; - /** - * Creation timestamp - */ - createdAt: string; - /** - * Last update timestamp - */ - updatedAt: string; - /** - * API key for the client - */ - apiKey?: string; - /** - * Webhook URL for the client - */ - webhookURL?: string; - /** - * Event webhook URL for the client - */ - eventWebhookURL?: string; - /** - * Secret for webhook authentication - */ - webhookSecret?: string; - /** - * Whether triggers are enabled for the client - */ - triggersEnabled: boolean; - /** - * Last subscription timestamp - */ - lastSubscribedAt?: string; - /** - * Client's subscription plan - */ - plan: string; + /** + * Auto-generated ID of the client + */ + autoId: number; + /** + * Unique ID of the client + */ + id: string; + /** + * Name of the client + */ + name: string; + /** + * Email of the client + */ + email: string; + /** + * Creation timestamp + */ + createdAt: string; + /** + * Last update timestamp + */ + updatedAt: string; + /** + * API key for the client + */ + apiKey?: string; + /** + * Webhook URL for the client + */ + webhookURL?: string; + /** + * Event webhook URL for the client + */ + eventWebhookURL?: string; + /** + * Secret for webhook authentication + */ + webhookSecret?: string; + /** + * Whether triggers are enabled for the client + */ + triggersEnabled: boolean; + /** + * Last subscription timestamp + */ + lastSubscribedAt?: string; + /** + * Client's subscription plan + */ + plan: string; }; export type ClientInfoResDTO = { - client: ClientDTO; - /** - * API key of the client - */ - apiKey: string; + client: ClientDTO; + /** + * API key of the client + */ + apiKey: string; }; export type ProjectReqDTO = { - /** - * The name of the project - */ - name: string; + /** + * The name of the project + */ + name: string; }; export type ProjectResDTO = { - /** - * The ID of the project - */ - id: string; - /** - * The name of the project - */ - name: string; + /** + * The ID of the project + */ + id: string; + /** + * The name of the project + */ + name: string; }; export type ProjectListResDTO = { - /** - * The list of projects - */ - items: Array<{ - [key: string]: unknown; - }>; + /** + * The list of projects + */ + items: Array<{ + [key: string]: unknown; + }>; }; export type InviteMemberReqDTO = { - /** - * The email of the member - */ - email: string; - /** - * The name of the member - */ - name: string; - /** - * The host to verify the member - */ - verifyHost: string; - /** - * The role that will be assignied to the invited user - */ - role?: 'admin' | 'developer'; + /** + * The email of the member + */ + email: string; + /** + * The name of the member + */ + name: string; + /** + * The host to verify the member + */ + verifyHost: string; + /** + * The role that will be assignied to the invited user + */ + role?: "admin" | "developer"; }; /** * The role that will be assignied to the invited user */ -export type role = 'admin' | 'developer'; +export type role = "admin" | "developer"; export type MemberResDTO = { - /** - * The email of the member - */ - email: string; - /** - * The uuid identifier for the member - */ - id: string; - /** - * The name of the member - */ - name: string; - /** - * The creation date of the member record - */ - createdAt?: string; - /** - * The role that is assigned to the member - */ - role: 'admin' | 'developer'; - /** - * The last update date of the member record - */ - updatedAt?: string; + /** + * The email of the member + */ + email: string; + /** + * The uuid identifier for the member + */ + id: string; + /** + * The name of the member + */ + name: string; + /** + * The creation date of the member record + */ + createdAt?: string; + /** + * The role that is assigned to the member + */ + role: "admin" | "developer"; + /** + * The last update date of the member record + */ + updatedAt?: string; }; export type UpdateMemberReqDTO = { - /** - * The uuid identifier for the member - */ - memberId: string; - /** - * The role that is assigned to the member - */ - role: 'admin' | 'developer'; + /** + * The uuid identifier for the member + */ + memberId: string; + /** + * The role that is assigned to the member + */ + role: "admin" | "developer"; }; export type GenerateAPIKeyReqDTO = { - /** - * The name of the API key to be generated - */ - name: string; + /** + * The name of the API key to be generated + */ + name: string; }; export type APIKeyResDTO = { - /** - * The ID of the API key - */ - id: string; - /** - * The name of the API key - */ - name: string; - /** - * The creation date of the API key - */ - createdAt: string; - /** - * The last update date of the API key - */ - updatedAt: string; - /** - * The generated API key - */ - key: string; - /** - * Whether the API key is hidden - */ - isHidden: boolean; - /** - * The last used date of the API key - */ - lastUsed?: string; - /** - * The member of the API key - */ - member: { - [key: string]: unknown; - }; + /** + * The ID of the API key + */ + id: string; + /** + * The name of the API key + */ + name: string; + /** + * The creation date of the API key + */ + createdAt: string; + /** + * The last update date of the API key + */ + updatedAt: string; + /** + * The generated API key + */ + key: string; + /** + * Whether the API key is hidden + */ + isHidden: boolean; + /** + * The last used date of the API key + */ + lastUsed?: string; + /** + * The member of the API key + */ + member: { + [key: string]: unknown; + }; }; export type DeleteAPIKeyReqDTO = { - /** - * The ID of the API key to be deleted - */ - id: string; + /** + * The ID of the API key to be deleted + */ + id: string; }; export type DeleteAPIKeyResponseDTO = { - /** - * The status of the delete operation - */ - deleted: boolean; + /** + * The status of the delete operation + */ + deleted: boolean; }; export type SingleAppInfoResDTO = { - /** - * The unique identifier for the app - */ - appId: string; - /** - * The key of the app - */ - key: string; - /** - * The name of the app - */ - name: string; - /** - * The description of the app - */ - description: string; - /** - * The logo of the app - */ - logo?: string; - /** - * The categories of the app - */ - categories?: Array<(string)>; - /** - * The path of the app - */ - path?: string; - /** - * The documentation URL of the app - */ - docs?: string; - /** - * The configuration documentation text of the app - */ - configuration_docs_text?: string; - /** - * The status of the app - */ - status?: string; - /** - * The documentation text of the app - */ - documentation_doc_text?: string; - /** - * The test connectors of the app - */ - testConnectors?: Array<{ - [key: string]: unknown; - }>; - /** - * Indicates if the app has no authentication - */ - no_auth?: boolean; - /** - * The authentication schemes of the app - */ - auth_schemes?: Array<{ - [key: string]: unknown; - }>; - /** - * The metadata of the app - */ - meta?: unknown; - /** - * The yaml of the app - */ - yaml?: unknown; + /** + * The unique identifier for the app + */ + appId: string; + /** + * The key of the app + */ + key: string; + /** + * The name of the app + */ + name: string; + /** + * The description of the app + */ + description: string; + /** + * The logo of the app + */ + logo?: string; + /** + * The categories of the app + */ + categories?: Array; + /** + * The path of the app + */ + path?: string; + /** + * The documentation URL of the app + */ + docs?: string; + /** + * The configuration documentation text of the app + */ + configuration_docs_text?: string; + /** + * The status of the app + */ + status?: string; + /** + * The documentation text of the app + */ + documentation_doc_text?: string; + /** + * The test connectors of the app + */ + testConnectors?: Array<{ + [key: string]: unknown; + }>; + /** + * Indicates if the app has no authentication + */ + no_auth?: boolean; + /** + * The authentication schemes of the app + */ + auth_schemes?: Array<{ + [key: string]: unknown; + }>; + /** + * The metadata of the app + */ + meta?: unknown; + /** + * The yaml of the app + */ + yaml?: unknown; }; export type AddToolsReqDTO = { - /** - * The name of the tool - */ - name: string; - /** - * The OpenAPI specification in YAML format - */ - openApiSpecYaml: string; - /** - * The integration details in YAML format - */ - integrationYaml: string; + /** + * The name of the tool + */ + name: string; + /** + * The OpenAPI specification in YAML format + */ + openApiSpecYaml: string; + /** + * The integration details in YAML format + */ + integrationYaml: string; }; export type OpenAPISpecListResDTO = { - /** - * Unique identifier for the OpenAPI spec - */ - id: string; - /** - * Name of the OpenAPI spec - */ - name: string; - /** - * Client identifier - */ - clientId: string; - /** - * Last synchronization date and time - */ - lastSyncAt: string; - /** - * Creation date and time - */ - createdAt: string; - /** - * Last update date and time - */ - updatedAt: string; - /** - * The job status of the app - */ - status?: 'initialized' | 'running' | 'caching' | 'cancelled' | 'finished' | 'exited'; - /** - * Current state of the app FSM - */ - state?: 'preprocess' | 'validate' | 'prepare' | 'build' | 'push' | 'load' | 'finish'; + /** + * Unique identifier for the OpenAPI spec + */ + id: string; + /** + * Name of the OpenAPI spec + */ + name: string; + /** + * Client identifier + */ + clientId: string; + /** + * Last synchronization date and time + */ + lastSyncAt: string; + /** + * Creation date and time + */ + createdAt: string; + /** + * Last update date and time + */ + updatedAt: string; + /** + * The job status of the app + */ + status?: + | "initialized" + | "running" + | "caching" + | "cancelled" + | "finished" + | "exited"; + /** + * Current state of the app FSM + */ + state?: + | "preprocess" + | "validate" + | "prepare" + | "build" + | "push" + | "load" + | "finish"; }; /** * The job status of the app */ -export type status = 'initialized' | 'running' | 'caching' | 'cancelled' | 'finished' | 'exited'; +export type status = + | "initialized" + | "running" + | "caching" + | "cancelled" + | "finished" + | "exited"; /** * Current state of the app FSM */ -export type state = 'preprocess' | 'validate' | 'prepare' | 'build' | 'push' | 'load' | 'finish'; +export type state = + | "preprocess" + | "validate" + | "prepare" + | "build" + | "push" + | "load" + | "finish"; export type AddRepoURLResDTO = { - /** - * Repository URL - */ - repoUrl: string; + /** + * Repository URL + */ + repoUrl: string; }; export type DeleteToolsReqDTO = { - /** - * Name of the tool - */ - name: string; + /** + * Name of the tool + */ + name: string; }; export type DeleteToolsResDTO = { - /** - * Message indicating successful deletion of tools - */ - message: string; + /** + * Message indicating successful deletion of tools + */ + message: string; }; export type AddToolsRequestDTO = { - /** - * The name of the tool - */ - name: string; - /** - * The OpenAPI specification in YAML format - */ - open_api_spec_yaml: string; - /** - * The integration details in YAML format - */ - integration_yaml: string; + /** + * The name of the tool + */ + name: string; + /** + * The OpenAPI specification in YAML format + */ + open_api_spec_yaml: string; + /** + * The integration details in YAML format + */ + integration_yaml: string; }; export type AddRepoURLReqDTO = { - /** - * Repository URL - */ - repoUrl: string; + /** + * Repository URL + */ + repoUrl: string; }; export type AppQueryDTO = { - /** - * Category of the app - */ - category?: string; - /** - * Additional fields to include in the response - */ - additionalFields?: string; - /** - * Enter 'true' or 'false' - */ - includeLocal?: string; + /** + * Category of the app + */ + category?: string; + /** + * Additional fields to include in the response + */ + additionalFields?: string; + /** + * Enter 'true' or 'false' + */ + includeLocal?: string; }; export type AppInfoResponseDto = { - /** - * The ID of the app - */ - appId: string; - /** - * The key of the app - */ - key: string; - /** - * The name of the app - */ - name: string; - /** - * The description of the app - */ - description: string; - /** - * The logo of the app - */ - logo: string; - /** - * The categories of the app - */ - categories: string; - /** - * The tags of the app - */ - tags?: string; - /** - * The authentication schemes of the app - */ - auth_schemes?: unknown; - /** - * Indicates if the app is enabled - */ - enabled: boolean; - /** - * Indicates if the app has no authentication - */ - no_auth?: boolean; + /** + * The ID of the app + */ + appId: string; + /** + * The key of the app + */ + key: string; + /** + * The name of the app + */ + name: string; + /** + * The description of the app + */ + description: string; + /** + * The logo of the app + */ + logo: string; + /** + * The categories of the app + */ + categories: string; + /** + * The tags of the app + */ + tags?: string; + /** + * The authentication schemes of the app + */ + auth_schemes?: unknown; + /** + * Indicates if the app is enabled + */ + enabled: boolean; + /** + * Indicates if the app has no authentication + */ + no_auth?: boolean; }; export type AppListResDTO = { - /** - * List of app details - */ - items: Array; - /** - * Total number of pages - */ - totalPages: number; + /** + * List of app details + */ + items: Array; + /** + * Total number of pages + */ + totalPages: number; }; export type ExpectedInputFieldsDTO = { - /** - * Name of the field - */ - name: string; - /** - * Type of the field - */ - type: string; - /** - * Description of the field - */ - description: string; - /** - * Display name of the field - */ - display_name: string; - /** - * Default value of the field - */ - default: { - [key: string]: unknown; - }; - /** - * Whether the field is required - */ - required: boolean; - /** - * Whether the field is expected from customer - */ - expected_from_customer: boolean; - /** - * Whether the field is a secret - */ - is_secret: boolean; + /** + * Name of the field + */ + name: string; + /** + * Type of the field + */ + type: string; + /** + * Description of the field + */ + description: string; + /** + * Display name of the field + */ + display_name: string; + /** + * Default value of the field + */ + default: { + [key: string]: unknown; + }; + /** + * Whether the field is required + */ + required: boolean; + /** + * Whether the field is expected from customer + */ + expected_from_customer: boolean; + /** + * Whether the field is a secret + */ + is_secret: boolean; }; export type GetConnectorInfoResDTO = { - /** - * Unique identifier of the connector - */ - id?: string; - /** - * Authentication scheme used by the connector - */ - authScheme?: string; - /** - * Name of the connector - */ - name?: string; - /** - * Creation date of the connector - */ - createdAt?: string; - /** - * Last update date of the connector - */ - updatedAt?: string; - /** - * Flag to indicate if the connector is currently enabled - */ - enabled: boolean; - /** - * Flag to indicate if the connector has been deleted - */ - deleted?: boolean; - /** - * Application ID associated with the connector - */ - appId: string; - /** - * Default connector ID if one exists - */ - defaultConnectorId?: string; - /** - * Authentication configuration with sensitive data obscured - */ - authConfig: { - [key: string]: unknown; - }; - /** - * List of required fields expected from the customer - */ - expectedInputFields: Array; - /** - * Logo URL of the application associated with the connector - */ - logo: string; - /** - * Name of the application associated with the connector - */ - appName: string; - /** - * Flag to indicate if Composio authentication is used - */ - useComposioAuth: boolean; + /** + * Unique identifier of the connector + */ + id?: string; + /** + * Authentication scheme used by the connector + */ + authScheme?: string; + /** + * Name of the connector + */ + name?: string; + /** + * Creation date of the connector + */ + createdAt?: string; + /** + * Last update date of the connector + */ + updatedAt?: string; + /** + * Flag to indicate if the connector is currently enabled + */ + enabled: boolean; + /** + * Flag to indicate if the connector has been deleted + */ + deleted?: boolean; + /** + * Application ID associated with the connector + */ + appId: string; + /** + * Default connector ID if one exists + */ + defaultConnectorId?: string; + /** + * Authentication configuration with sensitive data obscured + */ + authConfig: { + [key: string]: unknown; + }; + /** + * List of required fields expected from the customer + */ + expectedInputFields: Array; + /** + * Logo URL of the application associated with the connector + */ + logo: string; + /** + * Name of the application associated with the connector + */ + appName: string; + /** + * Flag to indicate if Composio authentication is used + */ + useComposioAuth: boolean; }; /** * Authentication configuration */ export type AuthConfigDTO = { - scopes?: Array<(string)>; - user_scopes?: Array<(string)>; + scopes?: Array; + user_scopes?: Array; }; export type CreateConnectorPayloadDTO = { - /** - * Name of the connector - */ - name: string; - /** - * Authentication scheme - */ - authScheme?: string; - authConfig?: AuthConfigDTO; - /** - * Flag to indicate if Composio authentication should be used - */ - useComposioAuth?: boolean; - /** - * Composio App UUID to be used for authentication. Either specify this or appName - */ - appId?: string; - /** - * Name of the app to be used for authentication. Either specify this or appId - */ - appName?: string; - /** - * Flag to force new integration - */ - forceNewIntegration?: boolean; + /** + * Name of the connector + */ + name: string; + /** + * Authentication scheme + */ + authScheme?: string; + authConfig?: AuthConfigDTO; + /** + * Flag to indicate if Composio authentication should be used + */ + useComposioAuth?: boolean; + /** + * Composio App UUID to be used for authentication. Either specify this or appName + */ + appId?: string; + /** + * Name of the app to be used for authentication. Either specify this or appId + */ + appName?: string; + /** + * Flag to force new integration + */ + forceNewIntegration?: boolean; }; export type PatchConnectorReqDTO = { - /** - * Authentication configuration for the connector - */ - authConfig?: { - [key: string]: unknown; - }; - /** - * Flag to indicate if the connector is enabled - */ - enabled?: boolean; + /** + * Authentication configuration for the connector + */ + authConfig?: { + [key: string]: unknown; + }; + /** + * Flag to indicate if the connector is enabled + */ + enabled?: boolean; }; export type PatchConnectorResDTO = { - /** - * Status of the patch operation - */ - status: string; + /** + * Status of the patch operation + */ + status: string; }; /** * List of connectors */ export type ConnectorListItemDTO = { - /** - * Application name associated with the connector - */ - appName: string; - /** - * Count of connections for the connector - */ - _count: { - [key: string]: unknown; - }; - /** - * List of connections with their details and request logs count - */ - connections: Array<{ - [key: string]: unknown; - }>; - /** - * Unique identifier of the connector - */ - id: string; - member: MemberInfoResDTO; - /** - * Name of the connector - */ - name: string; - /** - * Authentication scheme used by the connector - */ - authScheme: string; - /** - * Creation date of the connector - */ - createdAt: string; - /** - * Last update date of the connector - */ - updatedAt: string; - /** - * Flag to indicate if the connector is enabled - */ - enabled: boolean; - /** - * Flag to indicate if the connector is deleted - */ - deleted?: boolean; - /** - * App ID associated with the connector - */ - appId: string; - /** - * Default connector ID if available - */ - defaultConnectorId?: string; + /** + * Application name associated with the connector + */ + appName: string; + /** + * Count of connections for the connector + */ + _count: { + [key: string]: unknown; + }; + /** + * List of connections with their details and request logs count + */ + connections: Array<{ + [key: string]: unknown; + }>; + /** + * Unique identifier of the connector + */ + id: string; + member: MemberInfoResDTO; + /** + * Name of the connector + */ + name: string; + /** + * Authentication scheme used by the connector + */ + authScheme: string; + /** + * Creation date of the connector + */ + createdAt: string; + /** + * Last update date of the connector + */ + updatedAt: string; + /** + * Flag to indicate if the connector is enabled + */ + enabled: boolean; + /** + * Flag to indicate if the connector is deleted + */ + deleted?: boolean; + /** + * App ID associated with the connector + */ + appId: string; + /** + * Default connector ID if available + */ + defaultConnectorId?: string; }; export type GetConnectorListResDTO = { - items: Array<{ - [key: string]: unknown; - }>; - /** - * Total number of pages available - */ - totalPages: number; - /** - * Current page number - */ - page: number; + items: Array<{ + [key: string]: unknown; + }>; + /** + * Total number of pages available + */ + totalPages: number; + /** + * Current page number + */ + page: number; }; export type PageInfo = { - total: number; - page: number; - pageSize: number; - totalPages: number; + total: number; + page: number; + pageSize: number; + totalPages: number; }; export type ConnectionWithAppData = { - id: string; - integrationId: string; - clientUniqueUserId?: string; - status: string; - data?: { - [key: string]: unknown; - }; - deleted?: boolean; - enabled?: boolean; - createdAt: string; - updatedAt: string; - appUniqueId: string; - appName: string; - logo?: string; - authConfig?: { - [key: string]: unknown; - }; - member: { - [key: string]: unknown; - }; - labels?: Array<(string)>; + id: string; + integrationId: string; + clientUniqueUserId?: string; + status: string; + data?: { + [key: string]: unknown; + }; + deleted?: boolean; + enabled?: boolean; + createdAt: string; + updatedAt: string; + appUniqueId: string; + appName: string; + logo?: string; + authConfig?: { + [key: string]: unknown; + }; + member: { + [key: string]: unknown; + }; + labels?: Array; }; export type GetConnectionsResult = { - connections: Array; - pageInfo: PageInfo; + connections: Array; + pageInfo: PageInfo; }; export type ConnectionParams = { - integrationId: string; - connectionParams?: { - [key: string]: unknown; - }; - isDisabled: boolean; - invocationCount: number; - id: string; - clientUniqueUserId?: string; - status: string; - data?: { - [key: string]: unknown; - }; - deleted?: boolean; - enabled?: boolean; - createdAt: string; - updatedAt: string; - appUniqueId: string; - appName: string; - logo?: string; - authConfig?: { - [key: string]: unknown; - }; - member: { - [key: string]: unknown; - }; - labels?: Array<(string)>; + integrationId: string; + connectionParams?: { + [key: string]: unknown; + }; + isDisabled: boolean; + invocationCount: number; + id: string; + clientUniqueUserId?: string; + status: string; + data?: { + [key: string]: unknown; + }; + deleted?: boolean; + enabled?: boolean; + createdAt: string; + updatedAt: string; + appUniqueId: string; + appName: string; + logo?: string; + authConfig?: { + [key: string]: unknown; + }; + member: { + [key: string]: unknown; + }; + labels?: Array; }; export type ToggleConnectedAccountResponseDTO = { - status: string; + status: string; }; export type ConnectionParamsHeaders = { - Authorization?: string; - 'x-request-id'?: string; + Authorization?: string; + "x-request-id"?: string; }; export type ConnectionParamsForAccount = { - scope?: string; - scopes?: string; - id_token?: string; - client_id?: string; - expires_in?: string; - token_type?: string; - callback_url?: string; - client_secret?: string; - code_verifier?: string; - refresh_token?: string; - headers?: { - [key: string]: unknown; - }; - queryParams?: { - [key: string]: unknown; - }; - base_url?: string; + scope?: string; + scopes?: string; + id_token?: string; + client_id?: string; + expires_in?: string; + token_type?: string; + callback_url?: string; + client_secret?: string; + code_verifier?: string; + refresh_token?: string; + headers?: { + [key: string]: unknown; + }; + queryParams?: { + [key: string]: unknown; + }; + base_url?: string; }; export type MetaApp = { - get_current_user_endpoint: string; + get_current_user_endpoint: string; }; export type Meta = { - app: { - [key: string]: unknown; - }; + app: { + [key: string]: unknown; + }; }; export type ConnectedAccountResponseDTO = { - integrationId: string; - appUniqueId: string; - memberInfo?: MemberInfoResDTO; - meta?: Meta; - isDisabled?: boolean; - id: string; - clientUniqueUserId: string; - appName: string; - entityId: string; - status: string; - enabled?: boolean; - createdAt: string; - updatedAt: string; + integrationId: string; + appUniqueId: string; + memberInfo?: MemberInfoResDTO; + meta?: Meta; + isDisabled?: boolean; + id: string; + clientUniqueUserId: string; + appName: string; + entityId: string; + status: string; + enabled?: boolean; + createdAt: string; + updatedAt: string; }; export type GetConnectionsResponseDto = { - items: Array; - totalPages: number; - page: number; + items: Array; + totalPages: number; + page: number; }; export type GetConnectionInfoResponseDTO = { - base_url: string; - parameters: Array; - body: { - [key: string]: unknown; - }; + base_url: string; + parameters: Array; + body: { + [key: string]: unknown; + }; }; export type Parameter = { - /** - * The name of the parameter. For example, 'x-api-key', 'Content-Type', etc., - */ - name: string; - /** - * The location of the parameter. Can be 'query' or 'header'. - */ - in: 'query' | 'header'; - /** - * The value of the parameter. For example, '1234567890', 'application/json', etc., - */ - value: string; + /** + * The name of the parameter. For example, 'x-api-key', 'Content-Type', etc., + */ + name: string; + /** + * The location of the parameter. Can be 'query' or 'header'. + */ + in: "query" | "header"; + /** + * The value of the parameter. For example, '1234567890', 'application/json', etc., + */ + value: string; }; export type Data = { - field1: string; - field2: string; + field1: string; + field2: string; }; export type AdditionalInfo = { - meta: string; + meta: string; }; export type GetConnectionsQueryDto = { - page?: number; - pageSize?: number; - appNames?: string; - integrationId?: string; - connectionId?: string; - user_uuid?: string; - showActiveOnly?: boolean; - status?: string; - showDisabled?: boolean; - labels?: Array<(string)>; + page?: number; + pageSize?: number; + appNames?: string; + integrationId?: string; + connectionId?: string; + user_uuid?: string; + showActiveOnly?: boolean; + status?: string; + showDisabled?: boolean; + labels?: Array; }; export type InitiateConnectionPayloadDto = { - data: { - [key: string]: unknown; - }; - integrationId: string; - redirectUri?: string; - userUuid?: string; - entityId?: string; - labels?: Array<(string)>; + data: { + [key: string]: unknown; + }; + integrationId: string; + redirectUri?: string; + userUuid?: string; + entityId?: string; + labels?: Array; }; export type UpdateConnectionLabelsPayloadDto = { - labels: Array<(string)>; + labels: Array; }; export type InitiateConnectionResponse = { - connectionStatus: string; - connectedAccountId: string; - redirectUrl?: string; + connectionStatus: string; + connectedAccountId: string; + redirectUrl?: string; }; export type ToolsExecuteReqDto = { - actionName: string; - runInSandbox: boolean; - input: { - [key: string]: unknown; - }; - nlaInput?: string; - authorizationData?: { - [key: string]: unknown; - }; - appSchema?: { - [key: string]: unknown; - }; - customDescription?: string; - systemPrompt?: string; + actionName: string; + runInSandbox: boolean; + input: { + [key: string]: unknown; + }; + nlaInput?: string; + authorizationData?: { + [key: string]: unknown; + }; + appSchema?: { + [key: string]: unknown; + }; + customDescription?: string; + systemPrompt?: string; }; export type DirectExecuteReqDto = { - endpoint: string; - base_url: string; - headers: { - [key: string]: unknown; - }; - queryParams: { - [key: string]: unknown; - }; - body?: { - [key: string]: unknown; - }; + endpoint: string; + base_url: string; + headers: { + [key: string]: unknown; + }; + queryParams: { + [key: string]: unknown; + }; + body?: { + [key: string]: unknown; + }; }; export type ActionExecutionResDto = { - data: { - [key: string]: unknown; - }; - error?: string; - successfull?: string; + data: { + [key: string]: unknown; + }; + error?: string; + successfull?: string; }; export type CustomAuthDTO = { - base_url?: string; - parameters: Array; - body?: { - [key: string]: unknown; - }; + base_url?: string; + parameters: Array; + body?: { + [key: string]: unknown; + }; }; export type ActionProxyRequestMethodDTO = { - /** - * The type of request body to use for the action. Defaults to 'none'. - */ - type?: 'formData' | 'urlEncoded' | 'raw' | 'binary' | 'graphql' | 'none'; - /** - * The data to be sent to the endpoint. This will override the body set in the connected account. - */ - data?: string; + /** + * The type of request body to use for the action. Defaults to 'none'. + */ + type?: "formData" | "urlEncoded" | "raw" | "binary" | "graphql" | "none"; + /** + * The data to be sent to the endpoint. This will override the body set in the connected account. + */ + data?: string; }; /** * The type of request body to use for the action. Defaults to 'none'. */ -export type type = 'formData' | 'urlEncoded' | 'raw' | 'binary' | 'graphql' | 'none'; +export type type = + | "formData" + | "urlEncoded" + | "raw" + | "binary" + | "graphql" + | "none"; export type ActionProxyRequestConfigDTO = { - /** - * The connected account uuid to use for the action. - */ - connectedAccountId: string; - /** - * The endpoint to call for the action. If the given url is relative, it will be resolved relative to the base_url set in the connected account info. - */ - endpoint: string; - /** - * The HTTP method to use for the action. - */ - method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; - parameters: Array; - /** - * The body to be sent to the endpoint. This can either be a JSON field or a string. - */ - body?: { - [key: string]: unknown; - }; + /** + * The connected account uuid to use for the action. + */ + connectedAccountId: string; + /** + * The endpoint to call for the action. If the given url is relative, it will be resolved relative to the base_url set in the connected account info. + */ + endpoint: string; + /** + * The HTTP method to use for the action. + */ + method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + parameters: Array; + /** + * The body to be sent to the endpoint. This can either be a JSON field or a string. + */ + body?: { + [key: string]: unknown; + }; }; /** * The HTTP method to use for the action. */ -export type method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; +export type method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; export type SessionInfoDTO = { - sessionId?: string; - metadata?: { - [key: string]: unknown; - }; + sessionId?: string; + metadata?: { + [key: string]: unknown; + }; }; export type ActionExecutionReqDTO = { - connectedAccountId?: string; - appName?: string; - entityId?: string; - endpoint?: string; - input?: { - [key: string]: unknown; - }; - sessionInfo?: SessionInfoDTO; - authConfig?: CustomAuthDTO; - text?: string; - customDescription?: string; - systemPrompt?: string; + connectedAccountId?: string; + appName?: string; + entityId?: string; + endpoint?: string; + input?: { + [key: string]: unknown; + }; + sessionInfo?: SessionInfoDTO; + authConfig?: CustomAuthDTO; + text?: string; + customDescription?: string; + systemPrompt?: string; }; export type ActionGetNLAInputsReqDTO = { - text: string; - customDescription?: string; - systemPrompt?: string; + text: string; + customDescription?: string; + systemPrompt?: string; }; export type ProxyExecutionReqDTO = { - endpoint: string; - connectedAccountId: string; + endpoint: string; + connectedAccountId: string; }; export type ActionDetailsMinimal = { - appId?: string; - appKey: string; - appName: string; - description: string; - displayName: string; - enabled: boolean; - logo: string; - name: string; - tags: Array<(string)>; - deprecated: boolean; + appId?: string; + appKey: string; + appName: string; + description: string; + displayName: string; + enabled: boolean; + logo: string; + name: string; + tags: Array; + deprecated: boolean; }; export type ActionDetails = { - parameters: { - [key: string]: unknown; - }; - response: { - [key: string]: unknown; - }; - appId?: string; - appKey: string; - appName: string; - description: string; - displayName: string; - enabled: boolean; - logo: string; - name: string; - tags: Array<(string)>; - deprecated: boolean; + parameters: { + [key: string]: unknown; + }; + response: { + [key: string]: unknown; + }; + appId?: string; + appKey: string; + appName: string; + description: string; + displayName: string; + enabled: boolean; + logo: string; + name: string; + tags: Array; + deprecated: boolean; }; export type ActionsListResponseDTO = { - items: Array; - page: number; - totalPages: number; + items: Array; + page: number; + totalPages: number; }; export type ActionsMinimalListResponseDTO = { - items: Array; - page: number; - totalPages: number; + items: Array; + page: number; + totalPages: number; }; export type AdvancedUseCaseSearchQueryDTO = { - useCase: string; - limit?: number; - maxActionsPerTask?: number; - minActionsPerTask?: number; - apps?: string; + useCase: string; + limit?: number; + maxActionsPerTask?: number; + minActionsPerTask?: number; + apps?: string; }; export type AdvancedUseCaseSearchTask = { - app: string; - actions: Array<(string)>; - description: string; - order: number; + app: string; + actions: Array; + description: string; + order: number; }; export type AdvancedUseCaseSearchResponse = { - items: Array; + items: Array; }; export type ExecuteActionResDTO = { - /** - * Indicates if the action was executed successfully - */ - response_data: boolean; - /** - * Details of the execution status - */ - execution_details: { - [key: string]: unknown; - }; + /** + * Indicates if the action was executed successfully + */ + response_data: boolean; + /** + * Details of the execution status + */ + execution_details: { + [key: string]: unknown; + }; }; export type ActionsQueryDTO = { - /** - * Names of the apps - */ - appNames?: string; - /** - * Use case - */ - useCase?: string; - /** - * Show enabled only - */ - showEnabledOnly?: boolean; - /** - * Limit - */ - limit?: number; - apps?: string; - actions?: string; - tags?: string; - usecaseLimit?: number; - filterImportantActions?: boolean; - showAll?: boolean; - page?: number; - offset?: number; + /** + * Names of the apps + */ + appNames?: string; + /** + * Use case + */ + useCase?: string; + /** + * Show enabled only + */ + showEnabledOnly?: boolean; + /** + * Limit + */ + limit?: number; + apps?: string; + actions?: string; + tags?: string; + usecaseLimit?: number; + filterImportantActions?: boolean; + showAll?: boolean; + page?: number; + offset?: number; }; export type ActionsControllerV1 = { - getAction: Array<{ - [key: string]: unknown; - }>; + getAction: Array<{ + [key: string]: unknown; + }>; }; export type OAuth2CallbackQueryDto = { - state: string; + state: string; }; export type RedirectUriDTO = { - redirectUri?: string; + redirectUri?: string; }; export type ListTriggersQueryDTO = { - /** - * Names of the apps - */ - appNames?: string; - /** - * IDs of the connected accounts - */ - connectedAccountIds?: string; - /** - * IDs of the triggers - */ - triggerIds?: string; - /** - * Integration ID - */ - integrationIds?: string; - /** - * Show enabled only - */ - showEnabledOnly?: boolean; + /** + * Names of the apps + */ + appNames?: string; + /** + * IDs of the connected accounts + */ + connectedAccountIds?: string; + /** + * IDs of the triggers + */ + triggerIds?: string; + /** + * Integration ID + */ + integrationIds?: string; + /** + * Show enabled only + */ + showEnabledOnly?: boolean; }; export type GetActiveTriggersQueryDTO = { - /** - * IDs of the connected accounts - */ - connectedAccountIds?: string; - /** - * IDs of the integrations - */ - integrationIds?: string; - /** - * IDs of the triggers - */ - triggerIds?: string; - /** - * Names of the triggers - */ - triggerNames?: string; - /** - * Page number - */ - page?: number; - /** - * Limit per page - */ - limit?: number; - /** - * Show disabled triggers - */ - showDisabled?: boolean; + /** + * IDs of the connected accounts + */ + connectedAccountIds?: string; + /** + * IDs of the integrations + */ + integrationIds?: string; + /** + * IDs of the triggers + */ + triggerIds?: string; + /** + * Names of the triggers + */ + triggerNames?: string; + /** + * Page number + */ + page?: number; + /** + * Limit per page + */ + limit?: number; + /** + * Show disabled triggers + */ + showDisabled?: boolean; }; export type GetLogsQueryDTO = { - /** - * ID of the connection - */ - connectionId?: string; - /** - * ID of the integration - */ - integrationId?: string; - /** - * Page number - */ - page?: number; - /** - * Limit per page - */ - limit?: number; + /** + * ID of the connection + */ + connectionId?: string; + /** + * ID of the integration + */ + integrationId?: string; + /** + * Page number + */ + page?: number; + /** + * Limit per page + */ + limit?: number; }; export type TriggerResDTO = { - /** - * Trigger name - */ - name: string; - /** - * Trigger display name - */ - display_name: string; - /** - * Trigger description - */ - description?: string; - /** - * Is trigger enabled - */ - enabled?: boolean; - /** - * Trigger configuration - */ - config?: { - [key: string]: unknown; - }; - /** - * Trigger payload - */ - payload?: { - [key: string]: unknown; - }; - /** - * Trigger logo URL - */ - logo?: string; - /** - * Trigger count - */ - count?: number; - /** - * App key - */ - appKey: string; - /** - * App ID - */ - appId: string; - /** - * App name - */ - appName: string; - /** - * Trigger instructions - */ - instructions?: string; - /** - * Trigger type - */ - type?: string; + /** + * Trigger name + */ + name: string; + /** + * Trigger display name + */ + display_name: string; + /** + * Trigger description + */ + description?: string; + /** + * Is trigger enabled + */ + enabled?: boolean; + /** + * Trigger configuration + */ + config?: { + [key: string]: unknown; + }; + /** + * Trigger payload + */ + payload?: { + [key: string]: unknown; + }; + /** + * Trigger logo URL + */ + logo?: string; + /** + * Trigger count + */ + count?: number; + /** + * App key + */ + appKey: string; + /** + * App ID + */ + appId: string; + /** + * App name + */ + appName: string; + /** + * Trigger instructions + */ + instructions?: string; + /** + * Trigger type + */ + type?: string; }; export type SingleTriggerResDTO = { - /** - * Trigger name - */ - name: string; - /** - * Trigger display name - */ - displayName: string; - /** - * Trigger description - */ - description: string; - /** - * Trigger type - */ - type: string; - /** - * App ID - */ - appId: string; - /** - * App name - */ - appName: string; - /** - * Trigger instructions - */ - instructions?: string; - /** - * Trigger payload - */ - payload: { - [key: string]: unknown; - }; - /** - * Trigger config - */ - config: { - [key: string]: unknown; - }; + /** + * Trigger name + */ + name: string; + /** + * Trigger display name + */ + displayName: string; + /** + * Trigger description + */ + description: string; + /** + * Trigger type + */ + type: string; + /** + * App ID + */ + appId: string; + /** + * App name + */ + appName: string; + /** + * Trigger instructions + */ + instructions?: string; + /** + * Trigger payload + */ + payload: { + [key: string]: unknown; + }; + /** + * Trigger config + */ + config: { + [key: string]: unknown; + }; }; /** * Trigger configuration */ export type TriggerConfig = { - /** - * Repository name - */ - repo: string; - /** - * Repository owner - */ - owner: string; + /** + * Repository name + */ + repo: string; + /** + * Repository owner + */ + owner: string; }; export type ActiveTriggerInstance = { - /** - * Trigger instance ID - */ - id?: string; - /** - * Connected account ID - */ - connectionId: string; - /** - * Trigger name - */ - triggerName: string; - /** - * Trigger data - */ - triggerData?: string; - triggerConfig: TriggerConfig; - /** - * Created at timestamp - */ - createdAt: string; - /** - * Updated at timestamp - */ - updatedAt: string; - /** - * Disabled at timestamp - */ - disabledAt?: string | null; + /** + * Trigger instance ID + */ + id?: string; + /** + * Connected account ID + */ + connectionId: string; + /** + * Trigger name + */ + triggerName: string; + /** + * Trigger data + */ + triggerData?: string; + triggerConfig: TriggerConfig; + /** + * Created at timestamp + */ + createdAt: string; + /** + * Updated at timestamp + */ + updatedAt: string; + /** + * Disabled at timestamp + */ + disabledAt?: string | null; }; export type PageInfoDTO = { - currentPage: number; - perPage: number; - totalPages: number; + currentPage: number; + perPage: number; + totalPages: number; }; export type ActiveTriggersResDTO = { - triggers: Array<{ - [key: string]: unknown; - }>; - pageInfo: Array; + triggers: Array<{ + [key: string]: unknown; + }>; + pageInfo: Array; }; export type TriggerLogsResDTO = { - data: Array; - pageInfo: PageInfoDTO; + data: Array; + pageInfo: PageInfoDTO; }; export type TriggerLogItemDTO = { - /** - * Client ID - */ - clientId: string; - /** - * Connection ID - */ - connectionId: string; - /** - * Error trigger - */ - errorTrigger?: string | null; - /** - * Trigger client error - */ - triggerClientError?: string | null; - /** - * Trigger client payload - */ - triggerClientPayload?: string | null; - /** - * Trigger provider payload - */ - triggerProviderPayload?: string | null; - /** - * Trigger name - */ - triggerName?: string | null; - /** - * Log ID - */ - id: string; - /** - * App key - */ - appKey: string; - /** - * Created at timestamp - */ - createdAt: string; + /** + * Client ID + */ + clientId: string; + /** + * Connection ID + */ + connectionId: string; + /** + * Error trigger + */ + errorTrigger?: string | null; + /** + * Trigger client error + */ + triggerClientError?: string | null; + /** + * Trigger client payload + */ + triggerClientPayload?: string | null; + /** + * Trigger provider payload + */ + triggerProviderPayload?: string | null; + /** + * Trigger name + */ + triggerName?: string | null; + /** + * Log ID + */ + id: string; + /** + * App key + */ + appKey: string; + /** + * Created at timestamp + */ + createdAt: string; }; export type HandleTriggerParamsDTO = { - /** - * The name of the app - */ - appName: string; - /** - * The client ID - */ - clientId: string; + /** + * The name of the app + */ + appName: string; + /** + * The client ID + */ + clientId: string; }; export type HandleTriggerBodyDTO = { - /** - * The trigger payload - */ - body: { - [key: string]: unknown; - }; + /** + * The trigger payload + */ + body: { + [key: string]: unknown; + }; }; export type EnableTriggerParamsDTO = { - /** - * The connected account ID - */ - connectedAccountId: string; - /** - * The trigger name - */ - triggerName: string; + /** + * The connected account ID + */ + connectedAccountId: string; + /** + * The trigger name + */ + triggerName: string; }; export type GetTriggerParamsDTO = { - /** - * The connected account ID - */ - triggerId: string; + /** + * The connected account ID + */ + triggerId: string; }; export type EnableTriggerBodyDTO = { - /** - * The trigger configuration - */ - triggerConfig: { - [key: string]: unknown; - }; - /** - * The verify host - */ - verifyHost?: string; + /** + * The trigger configuration + */ + triggerConfig: { + [key: string]: unknown; + }; + /** + * The verify host + */ + verifyHost?: string; }; export type SwitchTriggerStatusParamsDTO = { - /** - * The trigger instance ID - */ - triggerId: string; + /** + * The trigger instance ID + */ + triggerId: string; }; export type SwitchTriggerStatusBodyDTO = { - /** - * The new enabled status of the trigger - */ - enabled: boolean; + /** + * The new enabled status of the trigger + */ + enabled: boolean; }; export type TriggerInstanceParamsDTO = { - /** - * The trigger instance ID - */ - triggerInstanceId: string; + /** + * The trigger instance ID + */ + triggerInstanceId: string; }; export type SetCallbackUrlBodyDTO = { - /** - * The callback URL - */ - callbackURL: string; + /** + * The callback URL + */ + callbackURL: string; }; export type TriggerResponseDTO = { - /** - * The status of the operation - */ - status: string; - /** - * Optional message - */ - message?: string; - /** - * Optional trigger ID - */ - triggerId?: string; - /** - * Is new trigger. If true, the trigger was created just now or else it was already existing - */ - isNew?: boolean; + /** + * The status of the operation + */ + status: string; + /** + * Optional message + */ + message?: string; + /** + * Optional trigger ID + */ + triggerId?: string; + /** + * Is new trigger. If true, the trigger was created just now or else it was already existing + */ + isNew?: boolean; }; export type WebhookURLResponseDTO = { - /** - * The status of the operation - */ - status: string; - /** - * The callback URL if found - */ - callbackURL?: string; + /** + * The status of the operation + */ + status: string; + /** + * The callback URL if found + */ + callbackURL?: string; }; /** * The trigger details if found */ export type TriggerMetadataDTO = { - /** - * The unique identifier of the trigger - */ - id: string; - /** - * The connection identifier associated with the trigger - */ - connectionId: string; - /** - * The name of the trigger - */ - triggerName: string; - /** - * The data associated with the trigger - */ - triggerData: string; - /** - * The configuration of the trigger - */ - triggerConfig: { - [key: string]: unknown; - }; - /** - * The state of the trigger - */ - state: { - [key: string]: unknown; - }; - /** - * The creation date of the trigger - */ - createdAt: string; - /** - * The last update date of the trigger - */ - updatedAt: string; - /** - * The date when the trigger was disabled, if applicable - */ - disabledAt?: string; - /** - * The reason why the trigger was disabled, if applicable - */ - disabledReason?: string; + /** + * The unique identifier of the trigger + */ + id: string; + /** + * The connection identifier associated with the trigger + */ + connectionId: string; + /** + * The name of the trigger + */ + triggerName: string; + /** + * The data associated with the trigger + */ + triggerData: string; + /** + * The configuration of the trigger + */ + triggerConfig: { + [key: string]: unknown; + }; + /** + * The state of the trigger + */ + state: { + [key: string]: unknown; + }; + /** + * The creation date of the trigger + */ + createdAt: string; + /** + * The last update date of the trigger + */ + updatedAt: string; + /** + * The date when the trigger was disabled, if applicable + */ + disabledAt?: string; + /** + * The reason why the trigger was disabled, if applicable + */ + disabledReason?: string; }; export type GetTriggerResponseDTO = { - /** - * The status of the operation - */ - status: string; - trigger?: TriggerMetadataDTO; + /** + * The status of the operation + */ + status: string; + trigger?: TriggerMetadataDTO; }; export type GenerateCLISessionReqDTO = { - /** - * The channel name for the CLI session - */ - channel_name: string; + /** + * The channel name for the CLI session + */ + channel_name: string; }; export type GenerateCLISessionResDTO = { - /** - * The key for the CLI session - */ - key: string; + /** + * The key for the CLI session + */ + key: string; }; export type GetCLISessionResDTO = { - /** - * The client ID - */ - clientId: string; - /** - * The CLI code - */ - cliCode: string; + /** + * The client ID + */ + clientId: string; + /** + * The CLI code + */ + cliCode: string; }; export type VerifyCLICodeResDTO = { - /** - * The client ID - */ - clientId: string; - /** - * The CLI code - */ - cliCode: string; - /** - * The API key associated with the client - */ - apiKey: string; + /** + * The client ID + */ + clientId: string; + /** + * The CLI code + */ + cliCode: string; + /** + * The API key associated with the client + */ + apiKey: string; }; export type CLIQueryDTO = { - /** - * Unique key for CLI session - */ - key: string; - /** - * Code for CLI verification - */ - code?: string; + /** + * Unique key for CLI session + */ + key: string; + /** + * Code for CLI verification + */ + code?: string; }; export type MetadataReqDTO = { - /** - * The email associated with the metadata request - */ - email: string; - /** - * Additional metadata as a key-value pair - */ - metadata?: unknown; + /** + * The email associated with the metadata request + */ + email: string; + /** + * Additional metadata as a key-value pair + */ + metadata?: unknown; }; export type TriggersEnabledToggleReqDTO = { - /** - * Flag to enable or disable triggers - */ - enabled: boolean; + /** + * Flag to enable or disable triggers + */ + enabled: boolean; }; export type TriggersEnabledToggleResDTO = { - /** - * Message indicating the result of the toggle operation - */ - message: string; + /** + * Message indicating the result of the toggle operation + */ + message: string; }; export type TriggerToggleInfoResponseDTO = { - /** - * Indicates if triggers are enabled - */ - triggersEnabled: boolean; + /** + * Indicates if triggers are enabled + */ + triggersEnabled: boolean; }; export type ToggleTriggerStateResponseDTO = { - message: string; + message: string; }; export type MetadataQueryDTO = { - /** - * Email of the client - */ - email: string; + /** + * Email of the client + */ + email: string; }; /** * Metadata associated with the trigger log */ export type TriggerMetadata = { - /** - * The unique id of the log - */ - id: string; - /** - * The type of the log - */ - type: 'trigger'; - /** - * The date and time when the log was created - */ - createdAt: string; - /** - * The date and time when the log was updated - */ - updatedAt: string; - /** - * The provider of the log - */ - provider: string; - /** - * The client uuid of the log - */ - clientId: string; - /** - * The connection id of the log - */ - connectionId: string; - /** - * The trigger provider payload of the log - */ - triggerProviderPayload?: string; - triggerClientPayload?: string; - /** - * The trigger client error of the log - */ - triggerClientError?: string; - /** - * The trigger name of the log - */ - triggerName?: string; - /** - * The trigger client response of the log - */ - triggerClientResponse?: string; + /** + * The unique id of the log + */ + id: string; + /** + * The type of the log + */ + type: "trigger"; + /** + * The date and time when the log was created + */ + createdAt: string; + /** + * The date and time when the log was updated + */ + updatedAt: string; + /** + * The provider of the log + */ + provider: string; + /** + * The client uuid of the log + */ + clientId: string; + /** + * The connection id of the log + */ + connectionId: string; + /** + * The trigger provider payload of the log + */ + triggerProviderPayload?: string; + triggerClientPayload?: string; + /** + * The trigger client error of the log + */ + triggerClientError?: string; + /** + * The trigger name of the log + */ + triggerName?: string; + /** + * The trigger client response of the log + */ + triggerClientResponse?: string; }; export type ActionMetadata = { - /** - * The unique id of the log - */ - id: string; - /** - * The request sent to the provider - */ - request: string; - /** - * The response from the provider - */ - response?: string; - /** - * The error request sent to the provider - */ - errorRequest?: string; - /** - * The type of the log - */ - type: 'action'; - /** - * The date and time when the log was created - */ - createdAt: string; - /** - * The date and time when the log was updated - */ - updatedAt: string; - /** - * The provider of the log - */ - provider: string; - /** - * The client uuid of the log - */ - clientId: string; - /** - * The connection id of the log - */ - connectionId: string; - /** - * The action name of the log - */ - actionName: string; + /** + * The unique id of the log + */ + id: string; + /** + * The request sent to the provider + */ + request: string; + /** + * The response from the provider + */ + response?: string; + /** + * The error request sent to the provider + */ + errorRequest?: string; + /** + * The type of the log + */ + type: "action"; + /** + * The date and time when the log was created + */ + createdAt: string; + /** + * The date and time when the log was updated + */ + updatedAt: string; + /** + * The provider of the log + */ + provider: string; + /** + * The client uuid of the log + */ + clientId: string; + /** + * The connection id of the log + */ + connectionId: string; + /** + * The action name of the log + */ + actionName: string; }; export type TriggerLogData = { - /** - * The unique identifier of the trigger log - */ - id: string; - /** - * The connection identifier associated with the trigger log - */ - connectionId: string; - /** - * The client identifier associated with the trigger log - */ - clientId: string; - /** - * The status of the trigger log - */ - status: string; - /** - * The name of the application associated with the trigger log - */ - appName: string; - /** - * The creation date and time of the trigger log - */ - createdAt: string; - /** - * The type of the log - */ - type: 'trigger'; - meta: TriggerMetadata; + /** + * The unique identifier of the trigger log + */ + id: string; + /** + * The connection identifier associated with the trigger log + */ + connectionId: string; + /** + * The client identifier associated with the trigger log + */ + clientId: string; + /** + * The status of the trigger log + */ + status: string; + /** + * The name of the application associated with the trigger log + */ + appName: string; + /** + * The creation date and time of the trigger log + */ + createdAt: string; + /** + * The type of the log + */ + type: "trigger"; + meta: TriggerMetadata; }; export type ActionLogData = { - /** - * The unique identifier of the action log - */ - id: string; - /** - * The connection identifier associated with the action log - */ - connectionId: string; - /** - * The client identifier associated with the action log - */ - clientId: string; - /** - * The status of the action log - */ - status: string; - /** - * The name of the application associated with the action log - */ - appName: string; - /** - * The creation date and time of the action log - */ - createdAt: string; - /** - * The type of the log - */ - type: 'action'; - meta: ActionMetadata; + /** + * The unique identifier of the action log + */ + id: string; + /** + * The connection identifier associated with the action log + */ + connectionId: string; + /** + * The client identifier associated with the action log + */ + clientId: string; + /** + * The status of the action log + */ + status: string; + /** + * The name of the application associated with the action log + */ + appName: string; + /** + * The creation date and time of the action log + */ + createdAt: string; + /** + * The type of the log + */ + type: "action"; + meta: ActionMetadata; }; export type LogsResDTO = { - /** - * The cursor to get the next page of logs - */ - nextCursor?: string; - /** - * Logs data - */ - data: Array<{ - [key: string]: unknown; - }>; + /** + * The cursor to get the next page of logs + */ + nextCursor?: string; + /** + * Logs data + */ + data: Array<{ + [key: string]: unknown; + }>; }; export type GetLogsDTO = { - /** - * Type of the log - */ - type?: 'error' | 'info' | 'debug'; - /** - * Time interval for which data needs to be fetched - */ - time?: '5m' | '30m' | '6h' | '1d' | '1w' | '1month' | '1y'; - /** - * Status of the log - */ - status?: 'all' | 'success' | 'error'; - /** - * Search term in the log - */ - search?: string; - /** - * Integration UUID - */ - integrationId?: string; - /** - * Entity id - */ - entityId?: string; - /** - * Limit of the logs - */ - limit?: number; - /** - * Cursor for pagination - */ - cursor?: string; - /** - * Type of the log - */ - logsType?: string; - /** - * Session ID of the log - */ - sessionId?: string; + /** + * Type of the log + */ + type?: "error" | "info" | "debug"; + /** + * Time interval for which data needs to be fetched + */ + time?: "5m" | "30m" | "6h" | "1d" | "1w" | "1month" | "1y"; + /** + * Status of the log + */ + status?: "all" | "success" | "error"; + /** + * Search term in the log + */ + search?: string; + /** + * Integration UUID + */ + integrationId?: string; + /** + * Entity id + */ + entityId?: string; + /** + * Limit of the logs + */ + limit?: number; + /** + * Cursor for pagination + */ + cursor?: string; + /** + * Type of the log + */ + logsType?: string; + /** + * Session ID of the log + */ + sessionId?: string; }; /** * Type of the log */ -export type type2 = 'error' | 'info' | 'debug'; +export type type2 = "error" | "info" | "debug"; /** * Time interval for which data needs to be fetched */ -export type time = '5m' | '30m' | '6h' | '1d' | '1w' | '1month' | '1y'; +export type time = "5m" | "30m" | "6h" | "1d" | "1w" | "1month" | "1y"; /** * Status of the log */ -export type status2 = 'all' | 'success' | 'error'; +export type status2 = "all" | "success" | "error"; export type IngestDataDTO = { - /** - * Connection ID of the log - */ - connectionId?: string; - /** - * Session ID of the log - */ - sessionId?: string; - /** - * Type of the log - */ - logsType?: string; - /** - * Entity ID of the log - */ - entityId?: string; - /** - * Provider name of the log - */ - providerName: string; - /** - * Action name of the log - */ - actionName: string; - request: { - [key: string]: unknown; - }; - response: { - [key: string]: unknown; - }; - isError: boolean; + /** + * Connection ID of the log + */ + connectionId?: string; + /** + * Session ID of the log + */ + sessionId?: string; + /** + * Type of the log + */ + logsType?: string; + /** + * Entity ID of the log + */ + entityId?: string; + /** + * Provider name of the log + */ + providerName: string; + /** + * Action name of the log + */ + actionName: string; + request: { + [key: string]: unknown; + }; + response: { + [key: string]: unknown; + }; + isError: boolean; }; export type IngestDataResponseDTO = { - isIngested: boolean; + isIngested: boolean; }; export type TimePeriodReqDTO = { - /** - * Time period to get the data for - */ - lastTimePeriod?: 'DAY' | 'WEEK' | 'MONTH' | 'SIX_MONTH' | 'YEAR' | 'FIVE_YEAR'; + /** + * Time period to get the data for + */ + lastTimePeriod?: + | "DAY" + | "WEEK" + | "MONTH" + | "SIX_MONTH" + | "YEAR" + | "FIVE_YEAR"; }; /** * Time period to get the data for */ -export type lastTimePeriod = 'DAY' | 'WEEK' | 'MONTH' | 'SIX_MONTH' | 'YEAR' | 'FIVE_YEAR'; +export type lastTimePeriod = + | "DAY" + | "WEEK" + | "MONTH" + | "SIX_MONTH" + | "YEAR" + | "FIVE_YEAR"; /** * Action counts by app */ export type ActionByAppDTO = { - /** - * Name of the app - */ - appName: string; - /** - * Total count of actions for the app - */ - totalCount: number; + /** + * Name of the app + */ + appName: string; + /** + * Total count of actions for the app + */ + totalCount: number; }; /** * Action counts by status */ export type ActionByStatusDTO = { - /** - * Count of failed actions - */ - failed: number; - /** - * Count of successful actions - */ - success: number; + /** + * Count of failed actions + */ + failed: number; + /** + * Count of successful actions + */ + success: number; }; /** * Comprehensive trigger analytics data, presenting a breakdown by day, status, and provider for all triggers */ export type ActionAnalyticsDTO = { - /** - * Date of the action - */ - date: string; - byApp: ActionByAppDTO; - byStatus: ActionByStatusDTO; + /** + * Date of the action + */ + date: string; + byApp: ActionByAppDTO; + byStatus: ActionByStatusDTO; }; /** * Detailed integration analytics data, including a breakdown of connection count, trigger count, and request logs count for each integration */ export type IntegrationsWithCountsDTO = { - /** - * Unique identifier for the integration - */ - id: string; - /** - * Name of the app - */ - appName: string; - /** - * Name of the integration - */ - integrationName: string; - /** - * Count of connections for the integration - */ - connectionCount: number; - /** - * Count of triggers for the integration - */ - triggerCount: number; - /** - * Count of request logs for the integration - */ - requestLogsCount: number; + /** + * Unique identifier for the integration + */ + id: string; + /** + * Name of the app + */ + appName: string; + /** + * Name of the integration + */ + integrationName: string; + /** + * Count of connections for the integration + */ + connectionCount: number; + /** + * Count of triggers for the integration + */ + triggerCount: number; + /** + * Count of request logs for the integration + */ + requestLogsCount: number; }; /** * Comprehensive app-level analytics data, providing a breakdown of connection count, trigger count, and request logs count for each app */ export type AppNameCountDTO = { - /** - * Name of the app - */ - appName: string; - /** - * Count of connections for the app - */ - connectionCount: number; - /** - * Count of triggers for the app - */ - triggerCount: number; - /** - * Count of request logs for the app - */ - requestLogsCount: number; + /** + * Name of the app + */ + appName: string; + /** + * Count of connections for the app + */ + connectionCount: number; + /** + * Count of triggers for the app + */ + triggerCount: number; + /** + * Count of request logs for the app + */ + requestLogsCount: number; }; export type AnalyticsDataReqDTO = { - /** - * Time period to get the data for - */ - lastTimePeriod?: 'DAY' | 'WEEK' | 'MONTH' | 'SIX_MONTH' | 'YEAR' | 'FIVE_YEAR'; + /** + * Time period to get the data for + */ + lastTimePeriod?: + | "DAY" + | "WEEK" + | "MONTH" + | "SIX_MONTH" + | "YEAR" + | "FIVE_YEAR"; }; /** * Connection counts by entity */ export type ClientUniqueUserIdCountDTO = { - /** - * Client unique user id - */ - clientUniqueUserId: string; - /** - * Count of connections for the client unique user id - */ - count: number; + /** + * Client unique user id + */ + clientUniqueUserId: string; + /** + * Count of connections for the client unique user id + */ + count: number; }; /** * Entity-related analytics data, providing a breakdown by connections, actions, and triggers for each entity. This is include all entity info. */ export type AnalyticsEntityDataDTO = { - byConnections: Array; - /** - * Action counts by entity - */ - byActions: Array; - /** - * Trigger counts by entity - */ - byTriggers: Array; + byConnections: Array; + /** + * Action counts by entity + */ + byActions: Array; + /** + * Trigger counts by entity + */ + byTriggers: Array; }; export type AnalyticsDataResDTO = { - entity: AnalyticsEntityDataDTO; - actions: Array; - trigger: Array; - integrations: Array; - app: AppNameCountDTO; + entity: AnalyticsEntityDataDTO; + actions: Array; + trigger: Array; + integrations: Array; + app: AppNameCountDTO; }; export type TopEntitiesResDTO = { - /** - * Top entities by connection count - */ - entities: Array; + /** + * Top entities by connection count + */ + entities: Array; }; export type TConnectionCountDTO = { - /** - * Name of the entity - */ - clientUniqueUserId: string; - /** - * Count of connections for the entity - */ - count: number; + /** + * Name of the entity + */ + clientUniqueUserId: string; + /** + * Count of connections for the entity + */ + count: number; }; export type EntityQueryReqDTO = { - /** - * Query to get the data for - */ - query?: string; + /** + * Query to get the data for + */ + query?: string; }; export type WebhookReqDTO = { - /** - * Event Webhook URL - */ - eventWebhookURL: string; + /** + * Event Webhook URL + */ + eventWebhookURL: string; }; export type FetchQueryDTO = { - /** - * Start time of the event in ISO 8601 format - */ - startTime: string; - /** - * End time of the event in ISO 8601 format - */ - endTime: string; + /** + * Start time of the event in ISO 8601 format + */ + startTime: string; + /** + * End time of the event in ISO 8601 format + */ + endTime: string; }; export type WebhookSecretResDTO = { - /** - * Webhook secret - */ - webhookSecret: string; + /** + * Webhook secret + */ + webhookSecret: string; }; export type CreateCheckoutSessionReqDto = { - plan: 'HOBBY' | 'STARTER' | 'GROWTH' | 'ENTERPRISE' | 'STARTUP'; + plan: "HOBBY" | "STARTER" | "GROWTH" | "ENTERPRISE" | "STARTUP"; }; -export type plan = 'HOBBY' | 'STARTER' | 'GROWTH' | 'ENTERPRISE' | 'STARTUP'; +export type plan = "HOBBY" | "STARTER" | "GROWTH" | "ENTERPRISE" | "STARTUP"; export type SDKErrorResDTO = { - /** - * The status of the SDK error - */ - status: string; + /** + * The status of the SDK error + */ + status: string; }; export type IdentifyClientData = { - /** - * IdentifyClientReqDTO - */ - body?: IdentifyClientReqDTO; + /** + * IdentifyClientReqDTO + */ + body?: IdentifyClientReqDTO; }; export type IdentifyClientResponse = IdentifyClientResDTO; @@ -2286,10 +2336,10 @@ export type GetUserInfoResponse = ClientInfoResDTO; export type GetUserInfoError = unknown; export type AddProjectData = { - /** - * ProjectReqDTO - */ - body?: ProjectReqDTO; + /** + * ProjectReqDTO + */ + body?: ProjectReqDTO; }; export type AddProjectResponse = unknown; @@ -2297,9 +2347,9 @@ export type AddProjectResponse = unknown; export type AddProjectError = unknown; export type DeleteProjectData = { - path: { - projectId: string; - }; + path: { + projectId: string; + }; }; export type DeleteProjectResponse = unknown; @@ -2311,10 +2361,10 @@ export type GetProjectsResponse = ProjectListResDTO; export type GetProjectsError = unknown; export type GenerateApiKeyData = { - /** - * GenerateAPIKeyReqDTO - */ - body: GenerateAPIKeyReqDTO; + /** + * GenerateAPIKeyReqDTO + */ + body: GenerateAPIKeyReqDTO; }; export type GenerateApiKeyResponse = APIKeyResDTO; @@ -2326,9 +2376,9 @@ export type ListApiKeysResponse = Array; export type ListApiKeysError = unknown; export type DeleteApiKeyData = { - path: { - id: string; - }; + path: { + id: string; + }; }; export type DeleteApiKeyResponse = DeleteAPIKeyResponseDTO; @@ -2336,11 +2386,11 @@ export type DeleteApiKeyResponse = DeleteAPIKeyResponseDTO; export type DeleteApiKeyError = unknown; export type GetAppsData = { - query?: { - additionalFields?: string; - category?: string; - includeLocal?: string; - }; + query?: { + additionalFields?: string; + category?: string; + includeLocal?: string; + }; }; export type GetAppsResponse = AppListResDTO; @@ -2352,9 +2402,9 @@ export type GetOpenApiSpecsResponse = Array; export type GetOpenApiSpecsError = unknown; export type DeleteOpenApiSpecToolData = { - path: { - id: string; - }; + path: { + id: string; + }; }; export type DeleteOpenApiSpecToolResponse = unknown; @@ -2362,10 +2412,10 @@ export type DeleteOpenApiSpecToolResponse = unknown; export type DeleteOpenApiSpecToolError = unknown; export type AppControllerSendEmailToClientData = { - body?: unknown; - query?: { - adminToken?: string; - }; + body?: unknown; + query?: { + adminToken?: string; + }; }; export type AppControllerSendEmailToClientResponse = unknown; @@ -2373,9 +2423,9 @@ export type AppControllerSendEmailToClientResponse = unknown; export type AppControllerSendEmailToClientError = unknown; export type GetOpenApiSpecStatusData = { - path: { - id: string; - }; + path: { + id: string; + }; }; export type GetOpenApiSpecStatusResponse = unknown; @@ -2383,9 +2433,9 @@ export type GetOpenApiSpecStatusResponse = unknown; export type GetOpenApiSpecStatusError = unknown; export type GetAppData = { - path: { - appName: string; - }; + path: { + appName: string; + }; }; export type GetAppResponse = SingleAppInfoResDTO; @@ -2393,10 +2443,10 @@ export type GetAppResponse = SingleAppInfoResDTO; export type GetAppError = unknown; export type CreateConnectorData = { - /** - * CreateConnectorPayloadDTO - */ - body?: CreateConnectorPayloadDTO; + /** + * CreateConnectorPayloadDTO + */ + body?: CreateConnectorPayloadDTO; }; export type CreateConnectorResponse = GetConnectorInfoResDTO; @@ -2408,9 +2458,9 @@ export type ListAllConnectorsResponse = GetConnectorListResDTO; export type ListAllConnectorsError = unknown; export type GetConnectorInfoData = { - path: { - integrationId: string; - }; + path: { + integrationId: string; + }; }; export type GetConnectorInfoResponse = GetConnectorInfoResDTO; @@ -2418,13 +2468,13 @@ export type GetConnectorInfoResponse = GetConnectorInfoResDTO; export type GetConnectorInfoError = unknown; export type ModifyConnectorData = { - /** - * PatchConnectorReqDTO - */ - body?: PatchConnectorReqDTO; - path: { - integrationId: string; - }; + /** + * PatchConnectorReqDTO + */ + body?: PatchConnectorReqDTO; + path: { + integrationId: string; + }; }; export type ModifyConnectorResponse = PatchConnectorResDTO; @@ -2432,9 +2482,9 @@ export type ModifyConnectorResponse = PatchConnectorResDTO; export type ModifyConnectorError = unknown; export type DeleteConnectorData = { - path: { - integrationId: string; - }; + path: { + integrationId: string; + }; }; export type DeleteConnectorResponse = DeleteRowAPIDTO; @@ -2442,18 +2492,18 @@ export type DeleteConnectorResponse = DeleteRowAPIDTO; export type DeleteConnectorError = unknown; export type GetConnectionsData = { - query?: { - appNames?: string; - connectionId?: string; - integrationId?: string; - labels?: Array<(string)>; - page?: number; - pageSize?: number; - showActiveOnly?: boolean; - showDisabled?: boolean; - status?: string; - user_uuid?: string; - }; + query?: { + appNames?: string; + connectionId?: string; + integrationId?: string; + labels?: Array; + page?: number; + pageSize?: number; + showActiveOnly?: boolean; + showDisabled?: boolean; + status?: string; + user_uuid?: string; + }; }; export type GetConnectionsResponse = GetConnectionsResponseDto; @@ -2461,10 +2511,10 @@ export type GetConnectionsResponse = GetConnectionsResponseDto; export type GetConnectionsError = unknown; export type InitiateConnectionData = { - /** - * InitiateConnectionPayloadDto - */ - body?: InitiateConnectionPayloadDto; + /** + * InitiateConnectionPayloadDto + */ + body?: InitiateConnectionPayloadDto; }; export type InitiateConnectionResponse2 = InitiateConnectionResponse; @@ -2472,13 +2522,13 @@ export type InitiateConnectionResponse2 = InitiateConnectionResponse; export type InitiateConnectionError = unknown; export type UpdateConnectionDataData = { - /** - * UpdateConnectionLabelsPayloadDto - */ - body?: UpdateConnectionLabelsPayloadDto; - path: { - connectedAccountId: string; - }; + /** + * UpdateConnectionLabelsPayloadDto + */ + body?: UpdateConnectionLabelsPayloadDto; + path: { + connectedAccountId: string; + }; }; export type UpdateConnectionDataResponse = unknown; @@ -2486,9 +2536,9 @@ export type UpdateConnectionDataResponse = unknown; export type UpdateConnectionDataError = unknown; export type GetConnectionData = { - path: { - connectedAccountId: string; - }; + path: { + connectedAccountId: string; + }; }; export type GetConnectionResponse = ConnectedAccountResponseDTO; @@ -2496,9 +2546,9 @@ export type GetConnectionResponse = ConnectedAccountResponseDTO; export type GetConnectionError = unknown; export type DeleteConnectionData = { - path: { - connectedAccountId: string; - }; + path: { + connectedAccountId: string; + }; }; export type DeleteConnectionResponse = DeleteRowAPIDTO; @@ -2506,9 +2556,9 @@ export type DeleteConnectionResponse = DeleteRowAPIDTO; export type DeleteConnectionError = unknown; export type GetConnectionInfoData = { - path: { - connectedAccountId: string; - }; + path: { + connectedAccountId: string; + }; }; export type GetConnectionInfoResponse = GetConnectionInfoResponseDTO; @@ -2516,9 +2566,9 @@ export type GetConnectionInfoResponse = GetConnectionInfoResponseDTO; export type GetConnectionInfoError = unknown; export type DisableConnectionData = { - path: { - connectedAccountId: string; - }; + path: { + connectedAccountId: string; + }; }; export type DisableConnectionResponse = ToggleConnectedAccountResponseDTO; @@ -2526,9 +2576,9 @@ export type DisableConnectionResponse = ToggleConnectedAccountResponseDTO; export type DisableConnectionError = unknown; export type EnableConnectionData = { - path: { - connectedAccountId: string; - }; + path: { + connectedAccountId: string; + }; }; export type EnableConnectionResponse = ToggleConnectedAccountResponseDTO; @@ -2536,13 +2586,13 @@ export type EnableConnectionResponse = ToggleConnectedAccountResponseDTO; export type EnableConnectionError = unknown; export type ListTriggersData = { - query?: { - appNames?: string; - connectedAccountIds?: string; - integrationIds?: string; - showEnabledOnly?: boolean; - triggerIds?: string; - }; + query?: { + appNames?: string; + connectedAccountIds?: string; + integrationIds?: string; + showEnabledOnly?: boolean; + triggerIds?: string; + }; }; export type ListTriggersResponse = Array; @@ -2550,14 +2600,14 @@ export type ListTriggersResponse = Array; export type ListTriggersError = unknown; export type EnableTriggerData = { - /** - * EnableTriggerBodyDTO - */ - body?: EnableTriggerBodyDTO; - path: { - connectedAccountId: string; - triggerName: string; - }; + /** + * EnableTriggerBodyDTO + */ + body?: EnableTriggerBodyDTO; + path: { + connectedAccountId: string; + triggerName: string; + }; }; export type EnableTriggerResponse = TriggerResponseDTO; @@ -2565,15 +2615,15 @@ export type EnableTriggerResponse = TriggerResponseDTO; export type EnableTriggerError = unknown; export type GetActiveTriggersData = { - query?: { - connectedAccountIds?: string; - integrationIds?: string; - limit?: number; - page?: number; - showDisabled?: boolean; - triggerIds?: string; - triggerNames?: string; - }; + query?: { + connectedAccountIds?: string; + integrationIds?: string; + limit?: number; + page?: number; + showDisabled?: boolean; + triggerIds?: string; + triggerNames?: string; + }; }; export type GetActiveTriggersResponse = ActiveTriggersResDTO; @@ -2581,13 +2631,13 @@ export type GetActiveTriggersResponse = ActiveTriggersResDTO; export type GetActiveTriggersError = unknown; export type SwitchTriggerInstanceStatusData = { - /** - * SwitchTriggerStatusBodyDTO - */ - body?: SwitchTriggerStatusBodyDTO; - path: { - triggerId: string; - }; + /** + * SwitchTriggerStatusBodyDTO + */ + body?: SwitchTriggerStatusBodyDTO; + path: { + triggerId: string; + }; }; export type SwitchTriggerInstanceStatusResponse = TriggerResponseDTO; @@ -2595,9 +2645,9 @@ export type SwitchTriggerInstanceStatusResponse = TriggerResponseDTO; export type SwitchTriggerInstanceStatusError = unknown; export type DisableTriggerData = { - path: { - triggerInstanceId: string; - }; + path: { + triggerInstanceId: string; + }; }; export type DisableTriggerResponse = TriggerResponseDTO; @@ -2605,9 +2655,9 @@ export type DisableTriggerResponse = TriggerResponseDTO; export type DisableTriggerError = unknown; export type DeleteTriggerData = { - path: { - triggerInstanceId: string; - }; + path: { + triggerInstanceId: string; + }; }; export type DeleteTriggerResponse = DeleteRowAPIDTO; @@ -2615,10 +2665,10 @@ export type DeleteTriggerResponse = DeleteRowAPIDTO; export type DeleteTriggerError = unknown; export type SetCallbackUrlData = { - /** - * SetCallbackUrlBodyDTO - */ - body?: SetCallbackUrlBodyDTO; + /** + * SetCallbackUrlBodyDTO + */ + body?: SetCallbackUrlBodyDTO; }; export type SetCallbackUrlResponse = TriggerResponseDTO; @@ -2630,12 +2680,12 @@ export type GetWebhookUrlResponse = WebhookURLResponseDTO; export type GetWebhookUrlError = unknown; export type GetTriggerLogsData = { - query?: { - connectionId?: string; - integrationId?: string; - limit?: number; - page?: number; - }; + query?: { + connectionId?: string; + integrationId?: string; + limit?: number; + page?: number; + }; }; export type GetTriggerLogsResponse = TriggerLogsResDTO; @@ -2643,9 +2693,9 @@ export type GetTriggerLogsResponse = TriggerLogsResDTO; export type GetTriggerLogsError = unknown; export type GetTriggerInfoV2Data = { - path: { - triggerName: string; - }; + path: { + triggerName: string; + }; }; export type GetTriggerInfoV2Response = Array; @@ -2657,9 +2707,9 @@ export type GetSentryDnsResponse = unknown; export type GetSentryDnsError = unknown; export type ClearCacheData = { - headers?: { - 'X-ADMIN-TOKEN'?: string; - }; + headers?: { + "X-ADMIN-TOKEN"?: string; + }; }; export type ClearCacheResponse = unknown; @@ -2671,10 +2721,10 @@ export type GenerateCliSessionResponse = GenerateCLISessionResDTO; export type GenerateCliSessionError = unknown; export type GetCliCodeData = { - query: { - code?: string; - key: string; - }; + query: { + code?: string; + key: string; + }; }; export type GetCliCodeResponse = GetCLISessionResDTO; @@ -2682,10 +2732,10 @@ export type GetCliCodeResponse = GetCLISessionResDTO; export type GetCliCodeError = unknown; export type VerifyCliCodeData = { - query: { - code?: string; - key: string; - }; + query: { + code?: string; + key: string; + }; }; export type VerifyCliCodeResponse = VerifyCLICodeResDTO; @@ -2693,18 +2743,18 @@ export type VerifyCliCodeResponse = VerifyCLICodeResDTO; export type VerifyCliCodeError = unknown; export type GetLogsData = { - query?: { - cursor?: string; - entityId?: string; - integrationId?: string; - limit?: number; - logsType?: string; - search?: string; - sessionId?: string; - status?: 'all' | 'success' | 'error'; - time?: '5m' | '30m' | '6h' | '1d' | '1w' | '1month' | '1y'; - type?: 'error' | 'info' | 'debug'; - }; + query?: { + cursor?: string; + entityId?: string; + integrationId?: string; + limit?: number; + logsType?: string; + search?: string; + sessionId?: string; + status?: "all" | "success" | "error"; + time?: "5m" | "30m" | "6h" | "1d" | "1w" | "1month" | "1y"; + type?: "error" | "info" | "debug"; + }; }; export type GetLogsResponse = LogsResDTO; @@ -2712,10 +2762,10 @@ export type GetLogsResponse = LogsResDTO; export type GetLogsError = unknown; export type PostLogsData = { - /** - * IngestDataDTO - */ - body?: IngestDataDTO; + /** + * IngestDataDTO + */ + body?: IngestDataDTO; }; export type PostLogsResponse = IngestDataResponseDTO; @@ -2723,20 +2773,20 @@ export type PostLogsResponse = IngestDataResponseDTO; export type PostLogsError = unknown; export type ListActionsV2Data = { - query?: { - actions?: string; - appNames?: string; - apps?: string; - filterImportantActions?: boolean; - limit?: number; - offset?: number; - page?: number; - showAll?: boolean; - showEnabledOnly?: boolean; - tags?: string; - useCase?: string; - usecaseLimit?: number; - }; + query?: { + actions?: string; + appNames?: string; + apps?: string; + filterImportantActions?: boolean; + limit?: number; + offset?: number; + page?: number; + showAll?: boolean; + showEnabledOnly?: boolean; + tags?: string; + useCase?: string; + usecaseLimit?: number; + }; }; export type ListActionsV2Response = ActionsListResponseDTO; @@ -2744,20 +2794,20 @@ export type ListActionsV2Response = ActionsListResponseDTO; export type ListActionsV2Error = unknown; export type ListActionsMinimalV2Data = { - query?: { - actions?: string; - appNames?: string; - apps?: string; - filterImportantActions?: boolean; - limit?: number; - offset?: number; - page?: number; - showAll?: boolean; - showEnabledOnly?: boolean; - tags?: string; - useCase?: string; - usecaseLimit?: number; - }; + query?: { + actions?: string; + appNames?: string; + apps?: string; + filterImportantActions?: boolean; + limit?: number; + offset?: number; + page?: number; + showAll?: boolean; + showEnabledOnly?: boolean; + tags?: string; + useCase?: string; + usecaseLimit?: number; + }; }; export type ListActionsMinimalV2Response = ActionsListResponseDTO; @@ -2765,13 +2815,13 @@ export type ListActionsMinimalV2Response = ActionsListResponseDTO; export type ListActionsMinimalV2Error = unknown; export type ExecuteActionV2Data = { - /** - * ActionExecutionReqDTO - */ - body?: ActionExecutionReqDTO; - path: { - actionId: string; - }; + /** + * ActionExecutionReqDTO + */ + body?: ActionExecutionReqDTO; + path: { + actionId: string; + }; }; export type ExecuteActionV2Response = ActionExecutionResDto; @@ -2779,13 +2829,13 @@ export type ExecuteActionV2Response = ActionExecutionResDto; export type ExecuteActionV2Error = unknown; export type GetActionInputsV2Data = { - /** - * ActionGetNLAInputsReqDTO - */ - body?: ActionGetNLAInputsReqDTO; - path: { - actionId: string; - }; + /** + * ActionGetNLAInputsReqDTO + */ + body?: ActionGetNLAInputsReqDTO; + path: { + actionId: string; + }; }; export type GetActionInputsV2Response = unknown; @@ -2793,9 +2843,9 @@ export type GetActionInputsV2Response = unknown; export type GetActionInputsV2Error = unknown; export type GetActionV2Data = { - path: { - actionId: string; - }; + path: { + actionId: string; + }; }; export type GetActionV2Response = ActionDetails; @@ -2803,10 +2853,10 @@ export type GetActionV2Response = ActionDetails; export type GetActionV2Error = unknown; export type ExecuteActionProxyV2Data = { - /** - * ActionProxyRequestConfigDTO - */ - body?: ActionProxyRequestConfigDTO; + /** + * ActionProxyRequestConfigDTO + */ + body?: ActionProxyRequestConfigDTO; }; export type ExecuteActionProxyV2Response = ActionExecutionResDto; @@ -2814,13 +2864,13 @@ export type ExecuteActionProxyV2Response = ActionExecutionResDto; export type ExecuteActionProxyV2Error = unknown; export type AdvancedUseCaseSearchData = { - query: { - apps?: string; - limit?: number; - maxActionsPerTask?: number; - minActionsPerTask?: number; - useCase: string; - }; + query: { + apps?: string; + limit?: number; + maxActionsPerTask?: number; + minActionsPerTask?: number; + useCase: string; + }; }; export type AdvancedUseCaseSearchResponse2 = AdvancedUseCaseSearchResponse; @@ -2828,9 +2878,15 @@ export type AdvancedUseCaseSearchResponse2 = AdvancedUseCaseSearchResponse; export type AdvancedUseCaseSearchError = unknown; export type GetAnalyticsData = { - query?: { - lastTimePeriod?: 'DAY' | 'WEEK' | 'MONTH' | 'SIX_MONTH' | 'YEAR' | 'FIVE_YEAR'; - }; + query?: { + lastTimePeriod?: + | "DAY" + | "WEEK" + | "MONTH" + | "SIX_MONTH" + | "YEAR" + | "FIVE_YEAR"; + }; }; export type GetAnalyticsResponse = AnalyticsDataResDTO; @@ -2838,9 +2894,9 @@ export type GetAnalyticsResponse = AnalyticsDataResDTO; export type GetAnalyticsError = unknown; export type GetTopEntitiesData = { - query?: { - query?: string; - }; + query?: { + query?: string; + }; }; export type GetTopEntitiesResponse = TopEntitiesResDTO; @@ -2848,12 +2904,12 @@ export type GetTopEntitiesResponse = TopEntitiesResDTO; export type GetTopEntitiesError = unknown; export type UpdateWebhookData = { - /** - * WebhookReqDTO - */ - body?: WebhookReqDTO; + /** + * WebhookReqDTO + */ + body?: WebhookReqDTO; }; export type UpdateWebhookResponse = unknown; -export type UpdateWebhookError = unknown; \ No newline at end of file +export type UpdateWebhookError = unknown; diff --git a/js/src/sdk/index.spec.ts b/js/src/sdk/index.spec.ts index 21366166b5..a353752416 100644 --- a/js/src/sdk/index.spec.ts +++ b/js/src/sdk/index.spec.ts @@ -2,132 +2,138 @@ import { describe, it, expect } from "@jest/globals"; import { Composio } from "./index"; import { getTestConfig } from "../../config/getTestConfig"; import { client as axiosClient } from "./client/services.gen"; -import { BASE_ERROR_CODE_INFO, SDK_ERROR_CODES } from "./utils/errors/src/constants"; +import { + BASE_ERROR_CODE_INFO, + SDK_ERROR_CODES, +} from "./utils/errors/src/constants"; import AxiosMockAdapter from "axios-mock-adapter"; const { COMPOSIO_API_KEY, BACKEND_HERMES_URL } = getTestConfig(); describe("Basic SDK spec suite", () => { - it("should create a basic client", () => { - const client = new Composio(COMPOSIO_API_KEY); - expect(client).toBeInstanceOf(Composio); - }); - - it("should throw an error if apiKey is not provided", async () => { - const originalExit = process.exit; - - // @ts-expect-error - process.exit = jest.fn(); - expect(() => new Composio()).toThrow('🔑 API Key is not provided'); - process.exit = originalExit; - - }); - - it("should handle 404 error gracefully", async () => { - const client = new Composio(COMPOSIO_API_KEY); - const mock = new AxiosMockAdapter(axiosClient.instance); - mock.onGet("/api/v1/apps").reply(404, { detail: "Not found" }); - - try { - await client.apps.list(); - } catch (e: any) { - const errorCode = SDK_ERROR_CODES.BACKEND.NOT_FOUND; - const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; - expect(e.errCode).toBe(errorCode); - expect(e.message).toContain(errorInfo.message); - expect(e.description).toBe(errorInfo.description); - expect(e.errorId).toBeDefined(); - expect(e.name).toBe("ComposioError"); - expect(e.possibleFix).toBe(errorInfo.possibleFix); - } - - mock.reset(); - }); - - it("should handle 400 error gracefully", async () => { - const client = new Composio(COMPOSIO_API_KEY); - const mock = new AxiosMockAdapter(axiosClient.instance); - mock.onGet("/api/v1/apps").reply(400, { errors: ["Invalid request for apps"] }); - - try { - await client.apps.list(); - } catch (e: any) { - const errorCode = SDK_ERROR_CODES.BACKEND.BAD_REQUEST; - const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; - expect(e.errCode).toBe(errorCode); - expect(e.message).toContain("Validation Errors while making request to https://backend.composio.dev/api/v1/apps"); - expect(e.description).toContain("Invalid request for apps"); - } - - mock.reset(); - }); - - it("should handle 500 and 502 error gracefully", async () => { - const client = new Composio(COMPOSIO_API_KEY); - const mock = new AxiosMockAdapter(axiosClient.instance); - mock.onGet("/api/v1/apps").reply(500, { detail: "Internal Server Error" }); - - try { - await client.apps.list(); - } catch (e: any) { - const errorCode = SDK_ERROR_CODES.BACKEND.SERVER_ERROR; - const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; - expect(e.errCode).toBe(errorCode); - expect(e.message).toContain(errorInfo.message); - expect(e.description).toContain(errorInfo.description); - expect(e.errorId).toBeDefined(); - expect(e.name).toBe("ComposioError"); - expect(e.possibleFix).toContain(errorInfo.possibleFix); - } - - mock.onGet("/api/v1/apps").reply(502, { detail: "Bad Gateway" }); - - try { - const apps = await client.apps.list(); - } catch (e: any) { - const errorCode = SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE; - const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; - expect(e.errCode).toBe(errorCode); - expect(e.message).toContain(errorInfo.message); - expect(e.description).toContain(errorInfo.description); - expect(e.errorId).toBeDefined(); - expect(e.name).toBe("ComposioError"); - expect(e.possibleFix).toContain(errorInfo.possibleFix); - } - - mock.reset(); - }); - - it("should give request timeout error", async () => { - const client = new Composio(COMPOSIO_API_KEY); - const mock = new AxiosMockAdapter(axiosClient.instance); - mock.onGet("/api/v1/apps").reply(408, {}); - - try { - await client.apps.list(); - } catch (e: any) { - const errorCode = SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT; - const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; - expect(e.errCode).toBe(errorCode); - expect(e.message).toContain(errorInfo.message); - expect(e.description).toBe(errorInfo.description); - expect(e.possibleFix).toBe(errorInfo.possibleFix); - } - - mock.reset(); - }); - - it("syntax error handling", () => { - expect(() => new Composio()).toThrow('🔑 API Key is not provided'); - }); - - it("should get an entity and then fetch a connection", async () => { - const app = "github"; - const composio = new Composio(COMPOSIO_API_KEY, BACKEND_HERMES_URL); - const entity = composio.getEntity("default"); - - expect(entity.id).toBe("default"); - - const connection = await entity.getConnection({app: app!}); - expect(connection.appUniqueId).toBe(app); - }); + it("should create a basic client", () => { + const client = new Composio(COMPOSIO_API_KEY); + expect(client).toBeInstanceOf(Composio); + }); + + it("should throw an error if apiKey is not provided", async () => { + const originalExit = process.exit; + + // @ts-expect-error + process.exit = jest.fn(); + expect(() => new Composio()).toThrow("🔑 API Key is not provided"); + process.exit = originalExit; + }); + + it("should handle 404 error gracefully", async () => { + const client = new Composio(COMPOSIO_API_KEY); + const mock = new AxiosMockAdapter(axiosClient.instance); + mock.onGet("/api/v1/apps").reply(404, { detail: "Not found" }); + + try { + await client.apps.list(); + } catch (e: any) { + const errorCode = SDK_ERROR_CODES.BACKEND.NOT_FOUND; + const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; + expect(e.errCode).toBe(errorCode); + expect(e.message).toContain(errorInfo.message); + expect(e.description).toBe(errorInfo.description); + expect(e.errorId).toBeDefined(); + expect(e.name).toBe("ComposioError"); + expect(e.possibleFix).toBe(errorInfo.possibleFix); + } + + mock.reset(); + }); + + it("should handle 400 error gracefully", async () => { + const client = new Composio(COMPOSIO_API_KEY); + const mock = new AxiosMockAdapter(axiosClient.instance); + mock + .onGet("/api/v1/apps") + .reply(400, { errors: ["Invalid request for apps"] }); + + try { + await client.apps.list(); + } catch (e: any) { + const errorCode = SDK_ERROR_CODES.BACKEND.BAD_REQUEST; + const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; + expect(e.errCode).toBe(errorCode); + expect(e.message).toContain( + "Validation Errors while making request to https://backend.composio.dev/api/v1/apps" + ); + expect(e.description).toContain("Invalid request for apps"); + } + + mock.reset(); + }); + + it("should handle 500 and 502 error gracefully", async () => { + const client = new Composio(COMPOSIO_API_KEY); + const mock = new AxiosMockAdapter(axiosClient.instance); + mock.onGet("/api/v1/apps").reply(500, { detail: "Internal Server Error" }); + + try { + await client.apps.list(); + } catch (e: any) { + const errorCode = SDK_ERROR_CODES.BACKEND.SERVER_ERROR; + const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; + expect(e.errCode).toBe(errorCode); + expect(e.message).toContain(errorInfo.message); + expect(e.description).toContain(errorInfo.description); + expect(e.errorId).toBeDefined(); + expect(e.name).toBe("ComposioError"); + expect(e.possibleFix).toContain(errorInfo.possibleFix); + } + + mock.onGet("/api/v1/apps").reply(502, { detail: "Bad Gateway" }); + + try { + const apps = await client.apps.list(); + } catch (e: any) { + const errorCode = SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE; + const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; + expect(e.errCode).toBe(errorCode); + expect(e.message).toContain(errorInfo.message); + expect(e.description).toContain(errorInfo.description); + expect(e.errorId).toBeDefined(); + expect(e.name).toBe("ComposioError"); + expect(e.possibleFix).toContain(errorInfo.possibleFix); + } + + mock.reset(); + }); + + it("should give request timeout error", async () => { + const client = new Composio(COMPOSIO_API_KEY); + const mock = new AxiosMockAdapter(axiosClient.instance); + mock.onGet("/api/v1/apps").reply(408, {}); + + try { + await client.apps.list(); + } catch (e: any) { + const errorCode = SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT; + const errorInfo = BASE_ERROR_CODE_INFO[errorCode]; + expect(e.errCode).toBe(errorCode); + expect(e.message).toContain(errorInfo.message); + expect(e.description).toBe(errorInfo.description); + expect(e.possibleFix).toBe(errorInfo.possibleFix); + } + + mock.reset(); + }); + + it("syntax error handling", () => { + expect(() => new Composio()).toThrow("🔑 API Key is not provided"); + }); + + it("should get an entity and then fetch a connection", async () => { + const app = "github"; + const composio = new Composio(COMPOSIO_API_KEY, BACKEND_HERMES_URL); + const entity = composio.getEntity("default"); + + expect(entity.id).toBe("default"); + + const connection = await entity.getConnection({ app: app! }); + expect(connection.appUniqueId).toBe(app); + }); }); diff --git a/js/src/sdk/index.ts b/js/src/sdk/index.ts index 1e649ab7b7..2bc67f496d 100644 --- a/js/src/sdk/index.ts +++ b/js/src/sdk/index.ts @@ -1,218 +1,299 @@ -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'; +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" - }); - } + /** + * 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(); - logger.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}, Log level: ${loggingLevel.toUpperCase()}`); + ComposioSDKContext.apiKey = apiKeyParsed; + ComposioSDKContext.baseURL = baseURLParsed; + ComposioSDKContext.frameworkRuntime = runtime; + ComposioSDKContext.composioVersion = require( + getPackageJsonDir() + "/package.json" + ).version; - // Initialize the BackendClient with the parsed API key and base URL. - this.backendClient = new BackendClient(apiKeyParsed, baseURLParsed, runtime); + 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", + }); + } - // 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); + logger.info( + `Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}, Log level: ${loggingLevel.toUpperCase()}` + ); - this.checkForLatestVersionFromNPM(); - } + // Initialize the BackendClient with the parsed API key and base URL. + this.backendClient = new BackendClient( + apiKeyParsed, + baseURLParsed, + runtime + ); - /** - * 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; - - - if (isNewerVersion(latestVersion, currentVersionFromPackageJson)) { - console.warn(`🚀 Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`); - } - } catch (error) { - // Ignore and do nothing - } + // 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; + + if (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); + } + + /** + * 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; + if (integrationId === null && app === null) { + throw new Error("Both `integration_id` and `app` cannot be None"); } - 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; - if (integrationId === null && app === null) { - throw new Error( - "Both `integration_id` and `app` cannot be None" - ); + if (!integrationId) { + try { + const integrations = await this.integrations.list({ + appName: app!, + showDisabled: false, + }); + if (params.authScheme && integrations) { + integrations.items = integrations.items.filter( + (integration: any) => integration.authScheme === params.authScheme + ); } + integrationId = (integrations?.items[0] as any)?.id; + } catch (_) { + // do nothing + } + } - if (!integrationId) { - try { - const integrations = await this.integrations.list({ - appName: app!, - showDisabled: false - }) - if (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; + + if (integration) { + return { + expectedInputFields: integration.expectedInputFields, + integrationId: integration.id!, + authScheme: integration.authScheme as + | "OAUTH2" + | "OAUTH1" + | "API_KEY" + | "BASIC" + | "BEARER_TOKEN" + | "BASIC_WITH_JWT", + }; + } - let integration = integrationId ? (await this.integrations.get({ - integrationId: integrationId! - })) : undefined; + const appInfo = await this.apps.get({ + appKey: app!.toLocaleLowerCase(), + }); - if(integration) { - return { - expectedInputFields: integration.expectedInputFields, - integrationId: integration.id!, - authScheme: integration.authScheme as "OAUTH2" | "OAUTH1" | "API_KEY" | "BASIC" | "BEARER_TOKEN" | "BASIC_WITH_JWT" - } - } + const preferredAuthScheme = [ + "OAUTH2", + "OAUTH1", + "API_KEY", + "BASIC", + "BEARER_TOKEN", + "BASIC_WITH_JWT", + ]; - const appInfo = await this.apps.get({ - appKey: app!.toLocaleLowerCase() - }); + let schema: (typeof preferredAuthScheme)[number] | undefined = + params.authScheme; - const preferredAuthScheme = ["OAUTH2", "OAUTH1", "API_KEY", "BASIC", "BEARER_TOKEN", "BASIC_WITH_JWT"]; - - let schema: typeof preferredAuthScheme[number] | undefined = params.authScheme; - - if(!schema) { - for(const scheme of preferredAuthScheme) { - if(appInfo.auth_schemes?.map((_authScheme: any) => _authScheme.mode).includes(scheme)) { - schema = scheme; - break; - } - } + if (!schema) { + for (const scheme of preferredAuthScheme) { + if ( + 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; + 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; - if (!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}` - ); - } + if (!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; - if(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" - } - } + 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; + if (hasRelevantTestConnectors) { + integration = await this.integrations.create({ + appId: appInfo.appId, + name: `integration_${timestamp}`, + authScheme: schema, + authConfig: {}, + useComposioAuth: true, + }); - if(!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." - ); - } + return { + expectedInputFields: integration?.expectedInputFields!, + integrationId: integration?.id!, + authScheme: integration?.authScheme as + | "OAUTH2" + | "OAUTH1" + | "API_KEY" + | "BASIC" + | "BEARER_TOKEN" + | "BASIC_WITH_JWT", + }; + } - integration = await this.integrations.create({ - appId: appInfo.appId, - name: `integration_${timestamp}`, - authScheme: schema, - authConfig: {}, - useComposioAuth: false, - }); + if (!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." + ); + } - if(!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" - } + integration = await this.integrations.create({ + appId: appInfo.appId, + name: `integration_${timestamp}`, + authScheme: schema, + authConfig: {}, + useComposioAuth: false, + }); + + if (!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", + }; + } } diff --git a/js/src/sdk/models/Entity.spec.ts b/js/src/sdk/models/Entity.spec.ts index c7e40dc7a2..e78f9c2ec2 100644 --- a/js/src/sdk/models/Entity.spec.ts +++ b/js/src/sdk/models/Entity.spec.ts @@ -5,7 +5,7 @@ import { ConnectedAccounts } from "./connectedAccounts"; import { Integrations } from "./integrations"; describe("Entity class tests", () => { - let backendClient = getBackendClient(); + const backendClient = getBackendClient(); let entity: Entity; let triggerId: string; let connectedAccounts: ConnectedAccounts; @@ -25,7 +25,7 @@ describe("Entity class tests", () => { it("should create for different entities", async () => { const entityId = "test-entity"; const entity2 = new Entity(backendClient, entityId); - const connection = await entity2.initiateConnection({appName: "github"}); + const connection = await entity2.initiateConnection({ appName: "github" }); expect(connection.connectionStatus).toBe("INITIATED"); const connection2 = await connectedAccounts.get({ @@ -37,19 +37,23 @@ describe("Entity class tests", () => { it("get connection for github", async () => { const app = "github"; - const connection = await entity.getConnection({app}); + const connection = await entity.getConnection({ app }); expect(connection.appUniqueId).toBe(app); }); it("execute action", async () => { - const connectedAccount = await entity.getConnection({app: "github"}); + const connectedAccount = await entity.getConnection({ app: "github" }); expect(connectedAccount).toHaveProperty("id"); expect(connectedAccount).toHaveProperty("appUniqueId", "github"); const actionName = "GITHUB_GITHUB_API_ROOT".toLowerCase(); const requestBody = {}; - const executionResult = await entity.execute({actionName, params: requestBody, connectedAccountId: connectedAccount.id}); + const executionResult = await entity.execute({ + actionName, + params: requestBody, + connectedAccountId: connectedAccount.id, + }); expect(executionResult).toBeDefined(); expect(executionResult).toHaveProperty("successfull", true); expect(executionResult).toHaveProperty("data.authorizations_url"); @@ -57,10 +61,12 @@ describe("Entity class tests", () => { it("should have an Id of a connected account with label - primary", async () => { const entityW2Connection = new Entity(backendClient, "ckemvy"); - const getConnection = await entityW2Connection.getConnection({app: "github"}); + const getConnection = await entityW2Connection.getConnection({ + app: "github", + }); expect(getConnection).toHaveProperty("id"); }); - + it("get connections", async () => { const connections = await entity.getConnections(); expect(connections.length).toBeGreaterThan(0); @@ -89,7 +95,7 @@ describe("Entity class tests", () => { }); it("initiate connection", async () => { - const connection = await entity.initiateConnection({appName: "github"}); + const connection = await entity.initiateConnection({ appName: "github" }); expect(connection.connectionStatus).toBe("INITIATED"); }); }); diff --git a/js/src/sdk/models/Entity.ts b/js/src/sdk/models/Entity.ts index e4766a584d..f79e1aa9b1 100644 --- a/js/src/sdk/models/Entity.ts +++ b/js/src/sdk/models/Entity.ts @@ -30,10 +30,12 @@ const ZInitiateConnectionParams = z.object({ integrationId: z.string().optional(), authMode: z.string().optional(), connectionData: z.record(z.any()).optional(), - config:z.object({ - labels: z.array(z.string()).optional(), - redirectUrl: z.string().optional(), - }).optional(), + config: z + .object({ + labels: z.array(z.string()).optional(), + redirectUrl: z.string().optional(), + }) + .optional(), }); type TInitiateConnectionParams = z.infer; @@ -59,9 +61,19 @@ export class Entity { this.activeTriggers = new ActiveTriggers(this.backendClient); } - async execute({actionName, params, text, connectedAccountId}: TExecuteActionParams) { + async execute({ + actionName, + params, + text, + connectedAccountId, + }: TExecuteActionParams) { try { - ZExecuteActionParams.parse({actionName, params, text, connectedAccountId}); + ZExecuteActionParams.parse({ + actionName, + params, + text, + connectedAccountId, + }); const action = await this.actionsModel.get({ actionName: actionName, }); @@ -80,13 +92,19 @@ export class Entity { }, }); } - const connectedAccount = await this.getConnection({app: action.appKey, connectedAccountId}); - + const connectedAccount = await this.getConnection({ + app: action.appKey, + connectedAccountId, + }); + if (!connectedAccount) { - throw CEG.getCustomError(SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, { - message: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`, - description: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`, - }); + throw CEG.getCustomError( + SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, + { + message: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`, + description: `Could not find a connection with app='${action.appKey}' and entity='${this.id}'`, + } + ); } return this.actionsModel.execute({ actionName: actionName, @@ -103,7 +121,13 @@ export class Entity { } } - async getConnection({app, connectedAccountId}: {app?: string, connectedAccountId?: string}): Promise { + async getConnection({ + app, + connectedAccountId, + }: { + app?: string; + connectedAccountId?: string; + }): Promise { try { if (connectedAccountId) { return await this.connectedAccounts.get({ @@ -122,7 +146,6 @@ export class Entity { return null; } - for (const account of connectedAccounts.items!) { if (account?.labels && account?.labels.includes(LABELS.PRIMARY)) { latestAccount = account; @@ -165,20 +188,27 @@ export class Entity { config: { [key: string]: any } ) { try { - const connectedAccount = await this.getConnection({app}); + const connectedAccount = await this.getConnection({ app }); if (!connectedAccount) { - throw CEG.getCustomError(SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, { - description: `Could not find a connection with app='${app}' and entity='${this.id}'`, - }); + throw CEG.getCustomError( + SDK_ERROR_CODES.SDK.NO_CONNECTED_ACCOUNT_FOUND, + { + description: `Could not find a connection with app='${app}' and entity='${this.id}'`, + } + ); } - const trigger = await this.triggerModel.setup({connectedAccountId: connectedAccount.id!, triggerName, config}); + const trigger = await this.triggerModel.setup({ + connectedAccountId: connectedAccount.id!, + triggerName, + config, + }); return trigger; } catch (error) { throw CEG.handleAllError(error); } } - async disableTrigger(triggerId: string){ + async disableTrigger(triggerId: string) { try { await this.activeTriggers.disable({ triggerId: triggerId }); return { status: "success" }; @@ -220,10 +250,13 @@ export class Entity { } } - async initiateConnection(data: TInitiateConnectionParams): Promise { + async initiateConnection( + data: TInitiateConnectionParams + ): Promise { try { - const {appName, authMode, authConfig, integrationId, connectionData} = ZInitiateConnectionParams.parse(data); - const {redirectUrl, labels} = data.config || {}; + const { appName, authMode, authConfig, integrationId, connectionData } = + ZInitiateConnectionParams.parse(data); + const { redirectUrl, labels } = data.config || {}; // Get the app details from the client const app = await this.apps.get({ appKey: appName }); diff --git a/js/src/sdk/models/actions.spec.ts b/js/src/sdk/models/actions.spec.ts index de81223599..802ba2307a 100644 --- a/js/src/sdk/models/actions.spec.ts +++ b/js/src/sdk/models/actions.spec.ts @@ -5,73 +5,76 @@ import { Entity } from "./Entity"; import { ConnectedAccounts } from "./connectedAccounts"; describe("Apps class tests", () => { - let backendClient; - let actions: Actions; - let connectedAccouns: ConnectedAccounts + let backendClient; + let actions: Actions; + let connectedAccouns: ConnectedAccounts; - beforeAll(() => { - backendClient = getBackendClient(); - actions = new Actions(backendClient); - connectedAccouns = new ConnectedAccounts(backendClient); - }); + beforeAll(() => { + backendClient = getBackendClient(); + actions = new Actions(backendClient); + connectedAccouns = new ConnectedAccounts(backendClient); + }); - it("should get a specific action", async () => { - const actionName = "GITHUB_GITHUB_API_ROOT"; - const action = await actions.get({ actionName: actionName.toLowerCase() }); - expect(action).toHaveProperty('name', actionName); - }); + it("should get a specific action", async () => { + const actionName = "GITHUB_GITHUB_API_ROOT"; + const action = await actions.get({ actionName: actionName.toLowerCase() }); + expect(action).toHaveProperty("name", actionName); + }); - it("should get a list of actions", async () => { - const actionsList = await actions.list(); - expect(actionsList.items).toBeInstanceOf(Array); - expect(actionsList.items).not.toHaveLength(0); - }); + it("should get a list of actions", async () => { + const actionsList = await actions.list(); + expect(actionsList.items).toBeInstanceOf(Array); + expect(actionsList.items).not.toHaveLength(0); + }); - it("should get a list of actions from integrated apps in an account", async () => { - const actionsList = await actions.list({ - filterByAvailableApps: true - }); - expect(actionsList.items).toBeInstanceOf(Array); - expect(actionsList.items).not.toHaveLength(0); + it("should get a list of actions from integrated apps in an account", async () => { + const actionsList = await actions.list({ + filterByAvailableApps: true, }); + expect(actionsList.items).toBeInstanceOf(Array); + expect(actionsList.items).not.toHaveLength(0); + }); - - it("should execute an action with a connected account for GitHub", async () => { - - const actionName = "GITHUB_GITHUB_API_ROOT".toLowerCase(); - const connectedAccountsResult = await connectedAccouns.list({ appNames: 'github', status: 'ACTIVE' }); - expect(connectedAccountsResult.items).not.toHaveLength(0); - const connectionId = connectedAccountsResult.items[0].id; - - const executionResult = await actions.execute({ - actionName: actionName, - requestBody: { - connectedAccountId: connectionId, - input: {}, - appName: 'github' - } - }); - - expect(executionResult).toHaveProperty('successfull', true); - expect((executionResult as any).data).toHaveProperty('authorizations_url'); + it("should execute an action with a connected account for GitHub", async () => { + const actionName = "GITHUB_GITHUB_API_ROOT".toLowerCase(); + const connectedAccountsResult = await connectedAccouns.list({ + appNames: "github", + status: "ACTIVE", }); + expect(connectedAccountsResult.items).not.toHaveLength(0); + const connectionId = connectedAccountsResult.items[0].id; + const executionResult = await actions.execute({ + actionName: actionName, + requestBody: { + connectedAccountId: connectionId, + input: {}, + appName: "github", + }, + }); - it("should execute an action of noauth app", async () => { - const actionName = "codeinterpreter_execute_code"; - const input = { code_to_execute: 'print("Hello World");' }; + expect(executionResult).toHaveProperty("successfull", true); + expect((executionResult as any).data).toHaveProperty("authorizations_url"); + }); - const executionResult = await actions.execute({ - actionName, - requestBody: { - input: input, - appName: "codeinterpreter", - } - }); + it("should execute an action of noauth app", async () => { + const actionName = "codeinterpreter_execute_code"; + const input = { code_to_execute: 'print("Hello World");' }; - expect(executionResult).toHaveProperty('successfull', true); - //@ts-ignore - expect((executionResult as any).data).toHaveProperty('stdout', 'Hello World\n'); - expect((executionResult as any).data).toHaveProperty('stderr', ''); + const executionResult = await actions.execute({ + actionName, + requestBody: { + input: input, + appName: "codeinterpreter", + }, }); + + expect(executionResult).toHaveProperty("successfull", true); + //@ts-ignore + expect((executionResult as any).data).toHaveProperty( + "stdout", + "Hello World\n" + ); + expect((executionResult as any).data).toHaveProperty("stderr", ""); + }); }); diff --git a/js/src/sdk/models/actions.ts b/js/src/sdk/models/actions.ts index a5729b5f7a..fd07fd93f8 100644 --- a/js/src/sdk/models/actions.ts +++ b/js/src/sdk/models/actions.ts @@ -1,4 +1,8 @@ -import { ActionExecutionReqDTO, ActionProxyRequestConfigDTO, ActionsListResponseDTO } from "../client"; +import { + ActionExecutionReqDTO, + ActionProxyRequestConfigDTO, + ActionsListResponseDTO, +} from "../client"; import apiClient from "../client/client"; import { CEG } from "../utils/error"; import { BackendClient } from "./backendClient"; @@ -22,260 +26,261 @@ import { BackendClient } from "./backendClient"; */ export type GetListActionsData = { - /** - * Name of the apps like "github", "linear" separated by a comma - */ - apps?: string; - /** - * Filter by Action names - */ - actions?: string; - /** - * Filter by Action tags - */ - tags?: string; - /** - * Filter by use case - */ - useCase?: string | undefined; - /** - * Limit of use-cases based search - */ - usecaseLimit?: number; - /** - * Show all actions - i.e disable pagination - */ - showAll?: boolean; - /** - * Show actions enabled for the API Key - */ - showEnabledOnly?: boolean; - /** - * Use smart tag filtering - */ - filterImportantActions?: boolean; - /** - * Should search in available apps only - */ - filterByAvailableApps?: boolean; -} + /** + * Name of the apps like "github", "linear" separated by a comma + */ + apps?: string; + /** + * Filter by Action names + */ + actions?: string; + /** + * Filter by Action tags + */ + tags?: string; + /** + * Filter by use case + */ + useCase?: string | undefined; + /** + * Limit of use-cases based search + */ + usecaseLimit?: number; + /** + * Show all actions - i.e disable pagination + */ + showAll?: boolean; + /** + * Show actions enabled for the API Key + */ + showEnabledOnly?: boolean; + /** + * Use smart tag filtering + */ + filterImportantActions?: boolean; + /** + * Should search in available apps only + */ + filterByAvailableApps?: boolean; +}; export type Parameter = { - /** - * The name of the parameter. - */ - name: string; + /** + * The name of the parameter. + */ + name: string; - /** - * The location of the parameter (e.g., query, header). - */ - in: string; + /** + * The location of the parameter (e.g., query, header). + */ + in: string; - /** - * The value of the parameter. - */ - value: string | number; + /** + * The value of the parameter. + */ + value: string | number; }; export type CustomAuthData = { + /** + * The base URL for the custom authentication. + */ + base_url?: string; + + /** + * An array of parameters for the custom authentication. + */ + parameters: Parameter[]; + + /** + * An optional object containing the body for the custom authentication. + */ + body?: Record; +}; + +export type ExecuteActionData = { + /** + * The name of the action to execute. + */ + actionName: string; + requestBody?: { /** - * The base URL for the custom authentication. + * The unique identifier of the connection to use for executing the action. */ - base_url?: string; - + connectedAccountId?: string; /** - * An array of parameters for the custom authentication. + * An object containing the input parameters for the action. If you want to execute + * NLP based action (i.e text), you can use text parameter instead of input. */ - parameters: Parameter[]; - + input?: { + [key: string]: unknown; + }; + appName?: string; /** - * An optional object containing the body for the custom authentication. + * The text to supply to the action which will be automatically converted to + * appropriate input parameters. */ - body?: Record; -} + text?: string; -export type ExecuteActionData = { /** - * The name of the action to execute. + * The custom authentication configuration for executing the action. */ - actionName: string; - requestBody?: { - /** - * The unique identifier of the connection to use for executing the action. - */ - connectedAccountId?: string; - /** - * An object containing the input parameters for the action. If you want to execute - * NLP based action (i.e text), you can use text parameter instead of input. - */ - input?: { - [key: string]: unknown; - }; - appName?: string; - /** - * The text to supply to the action which will be automatically converted to - * appropriate input parameters. - */ - text?: string; - - /** - * The custom authentication configuration for executing the action. - */ - authConfig?: CustomAuthData; - }; + authConfig?: CustomAuthData; + }; }; export type ExecuteActionResponse = { + /** + * An object containing the details of the action execution. + */ + execution_details?: { /** - * An object containing the details of the action execution. - */ - execution_details?: { - /** - * A boolean indicating whether the action was executed successfully. - * - */ - executed?: boolean; - }; - /** - * An object containing the response data from the action execution. + * A boolean indicating whether the action was executed successfully. + * */ - response_data?: { - [key: string]: unknown; - }; + executed?: boolean; + }; + /** + * An object containing the response data from the action execution. + */ + response_data?: { + [key: string]: unknown; + }; }; export class Actions { - backendClient: BackendClient; + backendClient: BackendClient; - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; - } + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + } - /** - * Retrieves details of a specific action in the Composio platform by providing its action name. - * - * The response includes the action's name, display name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {GetActionData} data The data for the request. - * @returns {CancelablePromise} A promise that resolves to the details of the action. - * @throws {ApiError} If the request fails. - */ - async get(data: { actionName: string; }) { - try{ - const actions = await apiClient.actionsV2.getActionV2({ - path: { - actionId: data.actionName - } - }); + /** + * Retrieves details of a specific action in the Composio platform by providing its action name. + * + * The response includes the action's name, display name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {GetActionData} data The data for the request. + * @returns {CancelablePromise} A promise that resolves to the details of the action. + * @throws {ApiError} If the request fails. + */ + async get(data: { actionName: string }) { + try { + const actions = await apiClient.actionsV2.getActionV2({ + path: { + actionId: data.actionName, + }, + }); - return (actions.data!); - } catch(e){ - throw CEG.handleAllError(e) - } + return actions.data!; + } catch (e) { + throw CEG.handleAllError(e); } + } - /** - * Retrieves a list of all actions in the Composio platform. - * - * This method allows you to fetch a list of all the available actions. It supports pagination to handle large numbers of actions. The response includes an array of action objects, each containing information such as the action's name, display name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {GetListActionsData} data The data for the request. - * @returns {Promise} A promise that resolves to the list of all actions. - * @throws {ApiError} If the request fails. - */ - async list(data: GetListActionsData = {}): Promise { - try { + /** + * Retrieves a list of all actions in the Composio platform. + * + * This method allows you to fetch a list of all the available actions. It supports pagination to handle large numbers of actions. The response includes an array of action objects, each containing information such as the action's name, display name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {GetListActionsData} data The data for the request. + * @returns {Promise} A promise that resolves to the list of all actions. + * @throws {ApiError} If the request fails. + */ + async list(data: GetListActionsData = {}): Promise { + try { + let apps = data.apps; - let apps = data.apps; - - // Throw error if user has provided both filterByAvailableApps and apps - if(data?.filterByAvailableApps && data?.apps){ - throw new Error("Both filterByAvailableApps and apps cannot be provided together"); - } + // Throw error if user has provided both filterByAvailableApps and apps + if (data?.filterByAvailableApps && data?.apps) { + throw new Error( + "Both filterByAvailableApps and apps cannot be provided together" + ); + } - if(data?.filterByAvailableApps){ - // Todo: To create a new API to get all integrated apps for a user instead of fetching all apps - const integratedApps = await apiClient.appConnector.listAllConnectors(); - apps = integratedApps.data?.items.map((app)=> app?.appName).join(","); - } - - const response = await apiClient.actionsV2.listActionsV2({ - query: { - actions: data.actions, - apps: apps, - showAll: data.showAll, - tags: data.tags, - useCase: data.useCase as string, - filterImportantActions: data.filterImportantActions, - showEnabledOnly: data.showEnabledOnly, - usecaseLimit: data.usecaseLimit || undefined - } - }); - return response.data!; - } catch (error) { - throw CEG.handleAllError(error); - } + if (data?.filterByAvailableApps) { + // Todo: To create a new API to get all integrated apps for a user instead of fetching all apps + const integratedApps = await apiClient.appConnector.listAllConnectors(); + apps = integratedApps.data?.items.map((app) => app?.appName).join(","); + } + + const response = await apiClient.actionsV2.listActionsV2({ + query: { + actions: data.actions, + apps: apps, + showAll: data.showAll, + tags: data.tags, + useCase: data.useCase as string, + filterImportantActions: data.filterImportantActions, + showEnabledOnly: data.showEnabledOnly, + usecaseLimit: data.usecaseLimit || undefined, + }, + }); + return response.data!; + } catch (error) { + throw CEG.handleAllError(error); } + } - /** - * Executes a specific action in the Composio platform. - * - * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action. - * - * @param {ExecuteActionData} data The data for the request. - * @returns {Promise} A promise that resolves to the execution status and response data. - * @throws {ApiError} If the request fails. - */ - async execute(data: ExecuteActionData){ - try { - const { data: res } = await apiClient.actionsV2.executeActionV2({ - body: data.requestBody as unknown as ActionExecutionReqDTO, - path: { - actionId: data.actionName - } - }); - return res!; - } catch (error) { - throw CEG.handleAllError(error); - } + /** + * Executes a specific action in the Composio platform. + * + * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action. + * + * @param {ExecuteActionData} data The data for the request. + * @returns {Promise} A promise that resolves to the execution status and response data. + * @throws {ApiError} If the request fails. + */ + async execute(data: ExecuteActionData) { + try { + const { data: res } = await apiClient.actionsV2.executeActionV2({ + body: data.requestBody as unknown as ActionExecutionReqDTO, + path: { + actionId: data.actionName, + }, + }); + return res!; + } catch (error) { + throw CEG.handleAllError(error); } + } - async findActionEnumsByUseCase(data: { - apps: Array, - useCase: string, - limit?: number, - }): Promise> { - try { - const { data: res } = await apiClient.actionsV2.advancedUseCaseSearch({ - query: { - apps: data.apps.join(","), - useCase: data.useCase, - limit: data.limit || undefined - } - }); - return res!.items.map((item) => item.actions).flat() || []; - } catch (error) { - throw CEG.handleAllError(error); - } + async findActionEnumsByUseCase(data: { + apps: Array; + useCase: string; + limit?: number; + }): Promise> { + try { + const { data: res } = await apiClient.actionsV2.advancedUseCaseSearch({ + query: { + apps: data.apps.join(","), + useCase: data.useCase, + limit: data.limit || undefined, + }, + }); + return res!.items.map((item) => item.actions).flat() || []; + } catch (error) { + throw CEG.handleAllError(error); } + } - /** - * Executes a action using Composio Proxy - * - * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action. - * - * @param {ExecuteActionData} data The data for the request. - * @returns {Promise} A promise that resolves to the execution status and response data. - * @throws {ApiError} If the request fails. - */ + /** + * Executes a action using Composio Proxy + * + * This method allows you to trigger the execution of an action by providing its name and the necessary input parameters. The request includes the connected account ID to identify the app connection to use for the action, and the input parameters required by the action. The response provides details about the execution status and the response data returned by the action. + * + * @param {ExecuteActionData} data The data for the request. + * @returns {Promise} A promise that resolves to the execution status and response data. + * @throws {ApiError} If the request fails. + */ - async executeRequest(data: ActionProxyRequestConfigDTO){ - try { - const { data: res } = await apiClient.actionsV2.executeActionProxyV2({ - body: data as unknown as ActionProxyRequestConfigDTO - }); - return res!; - } catch (error) { - throw CEG.handleAllError(error); - } + async executeRequest(data: ActionProxyRequestConfigDTO) { + try { + const { data: res } = await apiClient.actionsV2.executeActionProxyV2({ + body: data as unknown as ActionProxyRequestConfigDTO, + }); + return res!; + } catch (error) { + throw CEG.handleAllError(error); } -} \ No newline at end of file + } +} diff --git a/js/src/sdk/models/activeTriggers.spec.ts b/js/src/sdk/models/activeTriggers.spec.ts index 3669864eb7..4ba7098414 100644 --- a/js/src/sdk/models/activeTriggers.spec.ts +++ b/js/src/sdk/models/activeTriggers.spec.ts @@ -3,31 +3,30 @@ import { getBackendClient } from "../testUtils/getBackendClient"; import { ActiveTriggers } from "./activeTriggers"; describe("Active Triggers class tests", () => { - let backendClient; - let activeTriggers: ActiveTriggers; - - beforeAll(() => { - backendClient = getBackendClient(); - activeTriggers = new ActiveTriggers(backendClient); - }); + let backendClient; + let activeTriggers: ActiveTriggers; - it("should retrieve a list of active triggers", async () => { - const activeTriggersList = await activeTriggers.list(); - expect(activeTriggersList).toBeInstanceOf(Array); - expect(activeTriggersList).not.toHaveLength(0); - }); + beforeAll(() => { + backendClient = getBackendClient(); + activeTriggers = new ActiveTriggers(backendClient); + }); - it("should retrieve details of a specific active trigger", async () => { - const activeTriggersList = await activeTriggers.list(); - const firstTrigger = activeTriggersList[0]; + it("should retrieve a list of active triggers", async () => { + const activeTriggersList = await activeTriggers.list(); + expect(activeTriggersList).toBeInstanceOf(Array); + expect(activeTriggersList).not.toHaveLength(0); + }); - if (!firstTrigger.id) { - throw new Error("Trigger ID is required"); - } - const activeTrigger = await activeTriggers.get({ - triggerId: firstTrigger.id as string - }); - expect(activeTrigger).toBeDefined(); - }); + it("should retrieve details of a specific active trigger", async () => { + const activeTriggersList = await activeTriggers.list(); + const firstTrigger = activeTriggersList[0]; + if (!firstTrigger.id) { + throw new Error("Trigger ID is required"); + } + const activeTrigger = await activeTriggers.get({ + triggerId: firstTrigger.id as string, + }); + expect(activeTrigger).toBeDefined(); + }); }); diff --git a/js/src/sdk/models/activeTriggers.ts b/js/src/sdk/models/activeTriggers.ts index f32151315d..cde2c76a47 100644 --- a/js/src/sdk/models/activeTriggers.ts +++ b/js/src/sdk/models/activeTriggers.ts @@ -1,103 +1,103 @@ - import { GetActiveTriggersData } from "../client/types.gen"; -import apiClient from "../client/client" +import apiClient from "../client/client"; import { BackendClient } from "./backendClient"; import { CEG } from "../utils/error"; type TActiveTrigger = { - id: string; - connectionId: string; - triggerName: string; - triggerData: string; - triggerConfig: Record; - state: Record; - createdAt: string; - updatedAt: string; - disabledAt: string | null; - disabledReason: string | null; -} + id: string; + connectionId: string; + triggerName: string; + triggerData: string; + triggerConfig: Record; + state: Record; + createdAt: string; + updatedAt: string; + disabledAt: string | null; + disabledReason: string | null; +}; export class ActiveTriggers { + backendClient: BackendClient; - backendClient: BackendClient; - - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; - } - /** - * Retrieves details of a specific active trigger in the Composio platform by providing its trigger name. - * - * The response includes the trigger's name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {GetActiveTriggerData} data The data for the request. - * @returns {CancelablePromise} A promise that resolves to the details of the active trigger. - * @throws {ApiError} If the request fails. - */ - async get({triggerId}: {triggerId: string}) { - try { - const {data} = await apiClient.triggers.getActiveTriggers({ - query:{ - triggerIds : `${triggerId}` - } - }) - return data?.triggers[0]; - } catch (error) { - throw CEG.handleAllError(error); - } + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + } + /** + * Retrieves details of a specific active trigger in the Composio platform by providing its trigger name. + * + * The response includes the trigger's name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {GetActiveTriggerData} data The data for the request. + * @returns {CancelablePromise} A promise that resolves to the details of the active trigger. + * @throws {ApiError} If the request fails. + */ + async get({ triggerId }: { triggerId: string }) { + try { + const { data } = await apiClient.triggers.getActiveTriggers({ + query: { + triggerIds: `${triggerId}`, + }, + }); + return data?.triggers[0]; + } catch (error) { + throw CEG.handleAllError(error); } + } + + /** + * Retrieves a list of all active triggers in the Composio platform. + * + * This method allows you to fetch a list of all the available active triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {ListActiveTriggersData} data The data for the request. + * @returns {CancelablePromise} A promise that resolves to the list of all active triggers. + * @throws {ApiError} If the request fails. + */ + async list(data: GetActiveTriggersData = {}) { + try { + const { data: response } = await apiClient.triggers.getActiveTriggers({ + query: data, + }); - /** - * Retrieves a list of all active triggers in the Composio platform. - * - * This method allows you to fetch a list of all the available active triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {ListActiveTriggersData} data The data for the request. - * @returns {CancelablePromise} A promise that resolves to the list of all active triggers. - * @throws {ApiError} If the request fails. - */ - async list(data: GetActiveTriggersData = {}) { - try { - const {data: response} = await apiClient.triggers.getActiveTriggers({ query: data }) - - return response?.triggers || []; - } catch (error) { - throw CEG.handleAllError(error); - } + return response?.triggers || []; + } catch (error) { + throw CEG.handleAllError(error); } + } - /** - * Enables the previously disabled trigger. - * - * @param {Object} data The data for the request. - * @param {string} data.triggerId Id of the trigger - * @returns {CancelablePromise>} A promise that resolves to the response of the enable request. - * @throws {ApiError} If the request fails. - */ - async enable(data: { triggerId: string }): Promise { - try { - await apiClient.triggers.switchTriggerInstanceStatus({ - path: data, - body: { - enabled: true - } - }); - return true; - } catch (error) { - throw CEG.handleAllError(error); - } + /** + * Enables the previously disabled trigger. + * + * @param {Object} data The data for the request. + * @param {string} data.triggerId Id of the trigger + * @returns {CancelablePromise>} A promise that resolves to the response of the enable request. + * @throws {ApiError} If the request fails. + */ + async enable(data: { triggerId: string }): Promise { + try { + await apiClient.triggers.switchTriggerInstanceStatus({ + path: data, + body: { + enabled: true, + }, + }); + return true; + } catch (error) { + throw CEG.handleAllError(error); } + } - async disable(data: { triggerId: string }) { - try { - await apiClient.triggers.switchTriggerInstanceStatus({ - path: data, - body: { - enabled: false - } - }); - return true; - } catch (error) { - throw CEG.handleAllError(error); - } + async disable(data: { triggerId: string }) { + try { + await apiClient.triggers.switchTriggerInstanceStatus({ + path: data, + body: { + enabled: false, + }, + }); + return true; + } catch (error) { + throw CEG.handleAllError(error); } + } } diff --git a/js/src/sdk/models/apps.spec.ts b/js/src/sdk/models/apps.spec.ts index dd4151fd43..388db34b76 100644 --- a/js/src/sdk/models/apps.spec.ts +++ b/js/src/sdk/models/apps.spec.ts @@ -3,66 +3,77 @@ import { getBackendClient } from "../testUtils/getBackendClient"; import { Apps } from "./apps"; describe("Apps class tests", () => { - let backendClient; - let apps: Apps; + let backendClient; + let apps: Apps; - beforeAll(() => { - backendClient = getBackendClient(); - apps = new Apps(backendClient); - }); + beforeAll(() => { + backendClient = getBackendClient(); + apps = new Apps(backendClient); + }); - it("should create an Apps instance and retrieve apps list", async () => { - const appsList = await apps.list(); - expect(appsList).toBeInstanceOf(Array); - expect(appsList).not.toHaveLength(0); + it("should create an Apps instance and retrieve apps list", async () => { + const appsList = await apps.list(); + expect(appsList).toBeInstanceOf(Array); + expect(appsList).not.toHaveLength(0); - const firstItem = appsList[0]; - expect(firstItem).toHaveProperty('appId'); - expect(firstItem).toHaveProperty('key'); - expect(firstItem).toHaveProperty('name'); - }); + const firstItem = appsList[0]; + expect(firstItem).toHaveProperty("appId"); + expect(firstItem).toHaveProperty("key"); + expect(firstItem).toHaveProperty("name"); + }); - it("should get details of a specific app by key", async () => { - const appKey = "github"; - const app = await apps.get({ appKey }); - expect(app).toBeDefined(); - expect(app).toHaveProperty('auth_schemes'); - // @ts-ignore - expect(app.auth_schemes[0]).toHaveProperty('auth_mode', 'OAUTH2'); - expect(app).toHaveProperty('key', appKey); - expect(app).toHaveProperty('name', 'github'); - expect(app).toHaveProperty('description'); - }); + it("should get details of a specific app by key", async () => { + const appKey = "github"; + const app = await apps.get({ appKey }); + expect(app).toBeDefined(); + expect(app).toHaveProperty("auth_schemes"); + // @ts-ignore + expect(app.auth_schemes[0]).toHaveProperty("auth_mode", "OAUTH2"); + expect(app).toHaveProperty("key", appKey); + expect(app).toHaveProperty("name", "github"); + expect(app).toHaveProperty("description"); + }); - it("should return undefined for an invalid app key", async () => { - try { - const app = await apps.get({ appKey: "nonexistent_key" }); - expect(app).toBeUndefined(); - } catch (error) { - expect(error).toBeDefined(); - } - }); + it("should return undefined for an invalid app key", async () => { + try { + const app = await apps.get({ appKey: "nonexistent_key" }); + expect(app).toBeUndefined(); + } catch (error) { + expect(error).toBeDefined(); + } + }); - it("should get required params for a specific app", async () => { - const inputFields = await apps.getRequiredParams("shopify"); + it("should get required params for a specific app", async () => { + const inputFields = await apps.getRequiredParams("shopify"); - expect(inputFields).toHaveProperty('availableAuthSchemes'); - expect(inputFields).toHaveProperty('authSchemes'); + expect(inputFields).toHaveProperty("availableAuthSchemes"); + expect(inputFields).toHaveProperty("authSchemes"); - const OAUTH2_SCHEME = "OAUTH2"; - expect(inputFields.availableAuthSchemes).toContain(OAUTH2_SCHEME); - expect(inputFields.authSchemes[OAUTH2_SCHEME].expected_from_user).toEqual(["client_id", "client_secret"]); - expect(inputFields.authSchemes[OAUTH2_SCHEME].optional_fields).toEqual(["oauth_redirect_uri", "scopes"]); - expect(inputFields.authSchemes[OAUTH2_SCHEME].required_fields).toEqual(["shop"]); - }); + const OAUTH2_SCHEME = "OAUTH2"; + expect(inputFields.availableAuthSchemes).toContain(OAUTH2_SCHEME); + expect(inputFields.authSchemes[OAUTH2_SCHEME].expected_from_user).toEqual([ + "client_id", + "client_secret", + ]); + expect(inputFields.authSchemes[OAUTH2_SCHEME].optional_fields).toEqual([ + "oauth_redirect_uri", + "scopes", + ]); + expect(inputFields.authSchemes[OAUTH2_SCHEME].required_fields).toEqual([ + "shop", + ]); + }); - it("should get required params for a specific auth scheme", async () => { - const OAUTH2_SCHEME = "OAUTH2"; - const requiredParams = await apps.getRequiredParamsForAuthScheme({appId: "shopify", authScheme: OAUTH2_SCHEME}); - expect(requiredParams).toEqual({ - required_fields: ["shop"], - optional_fields: ["oauth_redirect_uri", "scopes"], - expected_from_user: ["client_id", "client_secret"] - }); + it("should get required params for a specific auth scheme", async () => { + const OAUTH2_SCHEME = "OAUTH2"; + const requiredParams = await apps.getRequiredParamsForAuthScheme({ + appId: "shopify", + authScheme: OAUTH2_SCHEME, + }); + expect(requiredParams).toEqual({ + required_fields: ["shop"], + optional_fields: ["oauth_redirect_uri", "scopes"], + expected_from_user: ["client_id", "client_secret"], }); + }); }); diff --git a/js/src/sdk/models/apps.ts b/js/src/sdk/models/apps.ts index 8284c0a563..d95f33a249 100644 --- a/js/src/sdk/models/apps.ts +++ b/js/src/sdk/models/apps.ts @@ -1,11 +1,11 @@ -import { AppListResDTO, SingleAppInfoResDTO } from "../client"; -import apiClient from "../client/client" +import { AppListResDTO, SingleAppInfoResDTO } from "../client"; +import apiClient from "../client/client"; import { CEG } from "../utils/error"; import { BackendClient } from "./backendClient"; export type GetAppData = { - appKey: string; + appKey: string; }; export type GetAppResponse = SingleAppInfoResDTO; @@ -13,119 +13,126 @@ export type GetAppResponse = SingleAppInfoResDTO; export type ListAllAppsResponse = AppListResDTO; export type RequiredParamsResponse = { - required_fields: string[]; - expected_from_user: string[]; - optional_fields: string[]; + required_fields: string[]; + expected_from_user: string[]; + optional_fields: string[]; }; export type RequiredParamsFullResponse = { - availableAuthSchemes: string[]; - authSchemes: Record; + availableAuthSchemes: string[]; + authSchemes: Record; }; export class Apps { - backendClient: BackendClient; - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; + backendClient: BackendClient; + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + } + + /** + * Retrieves a list of all available apps in the Composio platform. + * + * This method allows clients to explore and discover the supported apps. It returns an array of app objects, each containing essential details such as the app's key, name, description, logo, categories, and unique identifier. + * + * @returns {Promise} A promise that resolves to the list of all apps. + * @throws {ApiError} If the request fails. + */ + async list() { + try { + const { data } = await apiClient.apps.getApps(); + return data?.items || []; + } catch (error) { + throw CEG.handleAllError(error); } - - - /** - * Retrieves a list of all available apps in the Composio platform. - * - * This method allows clients to explore and discover the supported apps. It returns an array of app objects, each containing essential details such as the app's key, name, description, logo, categories, and unique identifier. - * - * @returns {Promise} A promise that resolves to the list of all apps. - * @throws {ApiError} If the request fails. - */ - async list(){ - try { - const {data} = await apiClient.apps.getApps(); - return data?.items || []; - } catch (error) { - throw CEG.handleAllError(error); - } - } - - /** - * Retrieves details of a specific app in the Composio platform. - * - * This method allows clients to fetch detailed information about a specific app by providing its unique key. The response includes the app's name, key, status, description, logo, categories, authentication schemes, and other metadata. - * - * @param {GetAppData} data The data for the request, including the app's unique key. - * @returns {CancelablePromise} A promise that resolves to the details of the app. - * @throws {ApiError} If the request fails. - */ - async get(data: GetAppData){ - try { - const {data:response} = await apiClient.apps.getApp({ - path: { - appName: data.appKey - } - }); - if(!response) throw new Error("App not found"); - return response; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + /** + * Retrieves details of a specific app in the Composio platform. + * + * This method allows clients to fetch detailed information about a specific app by providing its unique key. The response includes the app's name, key, status, description, logo, categories, authentication schemes, and other metadata. + * + * @param {GetAppData} data The data for the request, including the app's unique key. + * @returns {CancelablePromise} A promise that resolves to the details of the app. + * @throws {ApiError} If the request fails. + */ + async get(data: GetAppData) { + try { + const { data: response } = await apiClient.apps.getApp({ + path: { + appName: data.appKey, + }, + }); + if (!response) throw new Error("App not found"); + return response; + } catch (error) { + throw CEG.handleAllError(error); } - - async getRequiredParams(appId: string): Promise { - try { - const appData = await this.get({ appKey: appId }); - if(!appData) throw new Error("App not found"); - const authSchemes = appData.auth_schemes; - const availableAuthSchemes = (authSchemes as Array<{ mode: string }>)?.map(scheme => scheme?.mode); - - const authSchemesObject: Record = {}; - - for (const scheme of authSchemes as Array<{ - mode: string; - fields: Array<{ - name: string; - required: boolean; - expected_from_customer: boolean; - }>; - }>) { - const name = scheme.mode; - authSchemesObject[name] = { - required_fields: [], - optional_fields: [], - expected_from_user: [] - }; - - scheme.fields.forEach((field) => { - const isExpectedForIntegrationSetup = field.expected_from_customer === false; - const isRequired = field.required; - - if (isExpectedForIntegrationSetup) { - if (isRequired) { - authSchemesObject[name].expected_from_user.push(field.name); - } else { - authSchemesObject[name].optional_fields.push(field.name); - } - } else { - authSchemesObject[name].required_fields.push(field.name); - } - }); + } + + async getRequiredParams(appId: string): Promise { + try { + const appData = await this.get({ appKey: appId }); + if (!appData) throw new Error("App not found"); + const authSchemes = appData.auth_schemes; + const availableAuthSchemes = ( + authSchemes as Array<{ mode: string }> + )?.map((scheme) => scheme?.mode); + + const authSchemesObject: Record = {}; + + for (const scheme of authSchemes as Array<{ + mode: string; + fields: Array<{ + name: string; + required: boolean; + expected_from_customer: boolean; + }>; + }>) { + const name = scheme.mode; + authSchemesObject[name] = { + required_fields: [], + optional_fields: [], + expected_from_user: [], + }; + + scheme.fields.forEach((field) => { + const isExpectedForIntegrationSetup = + field.expected_from_customer === false; + const isRequired = field.required; + + if (isExpectedForIntegrationSetup) { + if (isRequired) { + authSchemesObject[name].expected_from_user.push(field.name); + } else { + authSchemesObject[name].optional_fields.push(field.name); } - - return { - availableAuthSchemes, - authSchemes: authSchemesObject - }; - } catch (error) { - throw CEG.handleAllError(error); - } + } else { + authSchemesObject[name].required_fields.push(field.name); + } + }); + } + + return { + availableAuthSchemes, + authSchemes: authSchemesObject, + }; + } catch (error) { + throw CEG.handleAllError(error); } - - async getRequiredParamsForAuthScheme({appId, authScheme}: {appId: string, authScheme: string}): Promise { - try { - const params = await this.getRequiredParams(appId); - return params.authSchemes[authScheme]; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async getRequiredParamsForAuthScheme({ + appId, + authScheme, + }: { + appId: string; + authScheme: string; + }): Promise { + try { + const params = await this.getRequiredParams(appId); + return params.authSchemes[authScheme]; + } catch (error) { + throw CEG.handleAllError(error); } + } } - diff --git a/js/src/sdk/models/backendClient.spec.ts b/js/src/sdk/models/backendClient.spec.ts index ffe0e6cdee..39eb1f2637 100644 --- a/js/src/sdk/models/backendClient.spec.ts +++ b/js/src/sdk/models/backendClient.spec.ts @@ -4,23 +4,29 @@ import { BACKEND_CONFIG, getTestConfig } from "../../../config/getTestConfig"; import { BackendClient } from "./backendClient"; describe("Apps class tests", () => { - let backendClient; - let testConfig:BACKEND_CONFIG; + let backendClient; + let testConfig: BACKEND_CONFIG; - beforeAll(() => { - testConfig = getTestConfig(); - }); + beforeAll(() => { + testConfig = getTestConfig(); + }); - it("should create an Apps instance and retrieve apps list", async () => { - backendClient = new BackendClient(testConfig.COMPOSIO_API_KEY, testConfig.BACKEND_HERMES_URL); - }); + it("should create an Apps instance and retrieve apps list", async () => { + backendClient = new BackendClient( + testConfig.COMPOSIO_API_KEY, + testConfig.BACKEND_HERMES_URL + ); + }); - it("should throw an error if api key is not provided", async () => { - expect(() => new BackendClient("", testConfig.BACKEND_HERMES_URL)).toThrow('🔑 API Key Missing or Invalid'); - }); - - it("should throw and error if wrong base url is provided", async () => { - expect(() => new BackendClient(testConfig.COMPOSIO_API_KEY, "htt://wrong.url")).toThrow('🔗 Base URL htt://wrong.url is not valid'); - }); + it("should throw an error if api key is not provided", async () => { + expect(() => new BackendClient("", testConfig.BACKEND_HERMES_URL)).toThrow( + "🔑 API Key Missing or Invalid" + ); + }); + it("should throw and error if wrong base url is provided", async () => { + expect( + () => new BackendClient(testConfig.COMPOSIO_API_KEY, "htt://wrong.url") + ).toThrow("🔗 Base URL htt://wrong.url is not valid"); + }); }); diff --git a/js/src/sdk/models/backendClient.ts b/js/src/sdk/models/backendClient.ts index 2db93e3947..d0e635e4cf 100644 --- a/js/src/sdk/models/backendClient.ts +++ b/js/src/sdk/models/backendClient.ts @@ -1,5 +1,5 @@ -import apiClient from "../client/client" -import { client as axiosClient } from "../client/services.gen" +import apiClient from "../client/client"; +import { client as axiosClient } from "../client/services.gen"; import { setAxiosClientConfig } from "../utils/config"; import { CEG } from "../utils/error"; import { SDK_ERROR_CODES } from "../utils/errors/src/constants"; @@ -8,77 +8,77 @@ import { SDK_ERROR_CODES } from "../utils/errors/src/constants"; * Class representing the details required to initialize and configure the API client. */ export class BackendClient { - /** - * The API key used for authenticating requests. - */ - public apiKey: string; + /** + * The API key used for authenticating requests. + */ + public apiKey: string; - /** - * The base URL of the API against which requests will be made. - */ - public baseUrl: string; + /** + * The base URL of the API against which requests will be made. + */ + public baseUrl: string; - /** - * The runtime environment where the client is being used. - */ - public runtime: string; + /** + * The runtime environment where the client is being used. + */ + public runtime: string; - /** - * Creates an instance of apiClientDetails. - * @param {string} apiKey - The API key for client initialization. - * @param {string} baseUrl - The base URL for the API client. - * @param {string} runtime - The runtime environment identifier. - * @throws Will throw an error if the API key is not provided. - */ - constructor(apiKey: string, baseUrl: string, runtime?: string) { - this.runtime = runtime || ''; - this.apiKey = apiKey; - this.baseUrl = baseUrl; + /** + * Creates an instance of apiClientDetails. + * @param {string} apiKey - The API key for client initialization. + * @param {string} baseUrl - The base URL for the API client. + * @param {string} runtime - The runtime environment identifier. + * @throws Will throw an error if the API key is not provided. + */ + constructor(apiKey: string, baseUrl: string, runtime?: string) { + this.runtime = runtime || ""; + this.apiKey = apiKey; + this.baseUrl = baseUrl; - if (!apiKey) { - throw CEG.getCustomError(SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE,{}); - } - - // Validate baseUrl - if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) { - throw CEG.getCustomError(SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE,{ - message: `🔗 Base URL ${baseUrl} is not valid`, - description: "The composio backend URL provided is not valid" - }); - } - - this.initializeApiClient(); + if (!apiKey) { + throw CEG.getCustomError(SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE, {}); } - /** - * Retrieves the client ID from the user's information. - * @returns {Promise} A promise that resolves to the client ID. - * @throws Will throw an error if the HTTP request fails. - */ - public async getClientId(): Promise { - try { - const {data} = await apiClient.clientAuth.getUserInfo() - return data?.client?.id || ''; - } catch (error) { - throw CEG.handleAllError(error); - } + // Validate baseUrl + if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) { + throw CEG.getCustomError(SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE, { + message: `🔗 Base URL ${baseUrl} is not valid`, + description: "The composio backend URL provided is not valid", + }); } - /** - * Initializes the API client with the provided configuration. - * @private - */ - private initializeApiClient() { - axiosClient.setConfig({ - baseURL: this.baseUrl, - headers: { - 'X-API-KEY': `${this.apiKey}`, - 'X-SOURCE': 'js_sdk', - 'X-RUNTIME': this.runtime - }, - throwOnError: true - }); + this.initializeApiClient(); + } - setAxiosClientConfig(axiosClient.instance); + /** + * Retrieves the client ID from the user's information. + * @returns {Promise} A promise that resolves to the client ID. + * @throws Will throw an error if the HTTP request fails. + */ + public async getClientId(): Promise { + try { + const { data } = await apiClient.clientAuth.getUserInfo(); + return data?.client?.id || ""; + } catch (error) { + throw CEG.handleAllError(error); } + } + + /** + * Initializes the API client with the provided configuration. + * @private + */ + private initializeApiClient() { + axiosClient.setConfig({ + baseURL: this.baseUrl, + headers: { + "X-API-KEY": `${this.apiKey}`, + "X-SOURCE": "js_sdk", + "X-RUNTIME": this.runtime, + }, + throwOnError: true, + }); + + setAxiosClientConfig(axiosClient.instance); + } } diff --git a/js/src/sdk/models/connectedAccounts.spec.ts b/js/src/sdk/models/connectedAccounts.spec.ts index 7cfdde5141..500d74ab4f 100644 --- a/js/src/sdk/models/connectedAccounts.spec.ts +++ b/js/src/sdk/models/connectedAccounts.spec.ts @@ -3,59 +3,60 @@ import { getBackendClient } from "../testUtils/getBackendClient"; import { ConnectedAccounts } from "./connectedAccounts"; describe("ConnectedAccounts class tests", () => { - let backendClient; - let connectedAccounts: ConnectedAccounts; - - beforeAll(() => { - backendClient = getBackendClient(); - connectedAccounts = new ConnectedAccounts(backendClient); - }); - - it("should create a ConnectedAccounts instance and retrieve connections list", async () => { - // @ts-ignore - const connectionsData: TConnectionData = { - appNames: 'github' - }; - const connectionsList = await connectedAccounts.list(connectionsData); - expect(connectionsList.items).toBeInstanceOf(Array); - expect(connectionsList.items).not.toHaveLength(0); - - // @ts-ignore - const firstConnection = connectionsList.items[0]; - expect(firstConnection.appName).toBe('github'); - expect(firstConnection).toHaveProperty('clientUniqueUserId'); - expect(firstConnection).toHaveProperty('status'); - expect(firstConnection).toHaveProperty('connectionParams'); + let backendClient; + let connectedAccounts: ConnectedAccounts; + + beforeAll(() => { + backendClient = getBackendClient(); + connectedAccounts = new ConnectedAccounts(backendClient); + }); + + it("should create a ConnectedAccounts instance and retrieve connections list", async () => { + // @ts-ignore + const connectionsData: TConnectionData = { + appNames: "github", + }; + const connectionsList = await connectedAccounts.list(connectionsData); + expect(connectionsList.items).toBeInstanceOf(Array); + expect(connectionsList.items).not.toHaveLength(0); + + // @ts-ignore + const firstConnection = connectionsList.items[0]; + expect(firstConnection.appName).toBe("github"); + expect(firstConnection).toHaveProperty("clientUniqueUserId"); + expect(firstConnection).toHaveProperty("status"); + expect(firstConnection).toHaveProperty("connectionParams"); + }); + + it("should retrieve a specific connection", async () => { + // @ts-ignore + const connectionsData: TConnectionData = { + appNames: "github", + }; + const connectionsList = await connectedAccounts.list(connectionsData); + + const connectionId = connectionsList.items[0].id; + + const connection = await connectedAccounts.get({ + connectedAccountId: connectionId, }); + // @ts-ignore + expect(connection.id).toBe(connectionId); + }); + it("should retrieve a specific connection for entity", async () => { + // @ts-ignore + const connectionsData: TConnectionData = { + user_uuid: "default", + }; + const connectionsList = await connectedAccounts.list(connectionsData); - it("should retrieve a specific connection", async () => { + const connectionId = connectionsList.items[0].id; - // @ts-ignore - const connectionsData: TConnectionData = { - appNames: 'github' - }; - const connectionsList = await connectedAccounts.list(connectionsData); - - const connectionId = connectionsList.items[0].id; - - const connection = await connectedAccounts.get({ connectedAccountId: connectionId }); - // @ts-ignore - expect(connection.id).toBe(connectionId); + const connection = await connectedAccounts.get({ + connectedAccountId: connectionId, }); - - it("should retrieve a specific connection for entity", async () => { - // @ts-ignore - const connectionsData: TConnectionData = { - user_uuid: 'default' - }; - const connectionsList = await connectedAccounts.list(connectionsData); - - const connectionId = connectionsList.items[0].id; - - const connection = await connectedAccounts.get({ connectedAccountId: connectionId }); - // @ts-ignore - expect(connection.id).toBe(connectionId); - }); - + // @ts-ignore + expect(connection.id).toBe(connectionId); + }); }); diff --git a/js/src/sdk/models/connectedAccounts.ts b/js/src/sdk/models/connectedAccounts.ts index 16a7225af7..3384d8ccd6 100644 --- a/js/src/sdk/models/connectedAccounts.ts +++ b/js/src/sdk/models/connectedAccounts.ts @@ -1,182 +1,242 @@ - -import { InitiateConnectionPayloadDto, GetConnectionsResponseDto, GetConnectionInfoData, GetConnectionInfoResponse, GetConnectionsData } from "../client"; +import { + InitiateConnectionPayloadDto, + GetConnectionsResponseDto, + GetConnectionInfoData, + GetConnectionInfoResponse, + GetConnectionsData, + InitiateConnectionResponse2, +} from "../client"; import client from "../client/client"; -import apiClient from "../client/client" +import apiClient from "../client/client"; import { BackendClient } from "./backendClient"; import { Integrations } from "./integrations"; import { Apps } from "./apps"; import { CEG } from "../utils/error"; +import { SDK_ERROR_CODES } from "../utils/errors/src/constants"; -type ConnectedAccountsListData = GetConnectionsData['query'] & { appNames?: string }; +type ConnectedAccountsListData = GetConnectionsData["query"] & { + appNames?: string; +}; type InitiateConnectionDataReq = InitiateConnectionPayloadDto & { - data?: Record | unknown; - entityId?: string; - labels?: string[]; - integrationId?: string; - redirectUri?: string; - authMode?: string; - authConfig?: { [key: string]: any }, - appName?: string; -} + data?: Record | unknown; + entityId?: string; + labels?: string[]; + integrationId?: string; + redirectUri?: string; + authMode?: string; + authConfig?: { [key: string]: any }; + appName?: string; +}; export class ConnectedAccounts { - backendClient: BackendClient; - integrations: Integrations; - apps: Apps; - - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; - this.integrations = new Integrations(this.backendClient); - this.apps = new Apps(this.backendClient); - } - - async list(data: ConnectedAccountsListData): Promise { - try { - const res = await apiClient.connections.getConnections({ query: data }); - return res.data!; - } catch (error) { - throw CEG.handleAllError(error); - } + backendClient: BackendClient; + integrations: Integrations; + apps: Apps; + + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + this.integrations = new Integrations(this.backendClient); + this.apps = new Apps(this.backendClient); + } + + async list( + data: ConnectedAccountsListData + ): Promise { + try { + const res = await apiClient.connections.getConnections({ query: data }); + return res.data!; + } catch (error) { + throw CEG.handleAllError(error); } - - async create(data: InitiateConnectionPayloadDto) { - try { - const { data: res } = await apiClient.connections.initiateConnection({ body: data }); - //@ts-ignore - return new ConnectionRequest(res.connectionStatus, res.connectedAccountId, res.redirectUrl); - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async create(data: InitiateConnectionPayloadDto) { + try { + const { data: res } = (await apiClient.connections.initiateConnection({ + body: data, + })) as { data: InitiateConnectionResponse2 }; + + return new ConnectionRequest({ + connectionStatus: res.connectionStatus, + connectedAccountId: res.connectedAccountId, + redirectUri: res.redirectUrl ?? null, + }); + } catch (error) { + throw CEG.handleAllError(error); } - - async get(data: { connectedAccountId: string }) { - try { - const res = await apiClient.connections.getConnection({ path: data }); - return res.data; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async get(data: { connectedAccountId: string }) { + try { + const res = await apiClient.connections.getConnection({ path: data }); + return res.data; + } catch (error) { + throw CEG.handleAllError(error); } - - async delete(data: { connectedAccountId: string }) { - try { - const res = await apiClient.connections.deleteConnection({ path: data }); - return res.data; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async delete(data: { connectedAccountId: string }) { + try { + const res = await apiClient.connections.deleteConnection({ path: data }); + return res.data; + } catch (error) { + throw CEG.handleAllError(error); } - - async getAuthParams(data: { connectedAccountId: string }) { - try { - const res = await apiClient.connections.getConnection({ path: { connectedAccountId: data.connectedAccountId } }); - return res.data; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async getAuthParams(data: { connectedAccountId: string }) { + try { + const res = await apiClient.connections.getConnection({ + path: { connectedAccountId: data.connectedAccountId }, + }); + return res.data; + } catch (error) { + throw CEG.handleAllError(error); } - - async initiate(payload: InitiateConnectionDataReq): Promise { - try { - let { integrationId, entityId = 'default', labels, data = {}, redirectUri, authMode, authConfig, appName } = payload; - - if (!integrationId && authMode) { - const timestamp = new Date().toISOString().replace(/[-:.]/g, ""); - - if(!appName) throw new Error("appName is required when integrationId is not provided"); - if(!authMode) throw new Error("authMode is required when integrationId is not provided"); - if(!authConfig) throw new Error("authConfig is required when integrationId is not provided"); - - const app = await this.apps.get({ appKey: appName }); - const integration = await this.integrations.create({ - appId: app.appId!, - name: `integration_${timestamp}`, - authScheme: authMode, - authConfig: authConfig, - useComposioAuth: false, - }); - integrationId = integration?.id!; - } - - const res = await client.connections.initiateConnection({ - body: { - integrationId, - entityId, - labels, - redirectUri, - data, - } - }).then(res => res.data); - - return new ConnectionRequest({ - connectionStatus: res?.connectionStatus!, - connectedAccountId: res?.connectedAccountId!, - redirectUri: res?.redirectUrl! - }) - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async initiate( + payload: InitiateConnectionDataReq + ): Promise { + try { + let { + integrationId, + entityId = "default", + labels, + data = {}, + redirectUri, + authMode, + authConfig, + appName, + } = payload; + + if (!integrationId && authMode) { + const timestamp = new Date().toISOString().replace(/[-:.]/g, ""); + + if (!appName) + throw new Error( + "appName is required when integrationId is not provided" + ); + if (!authMode) + throw new Error( + "authMode is required when integrationId is not provided" + ); + if (!authConfig) + throw new Error( + "authConfig is required when integrationId is not provided" + ); + + const app = await this.apps.get({ appKey: appName }); + const integration = await this.integrations.create({ + appId: app.appId!, + name: `integration_${timestamp}`, + authScheme: authMode, + authConfig: authConfig, + useComposioAuth: false, + }); + integrationId = integration?.id!; + } + + const res = await client.connections + .initiateConnection({ + body: { + integrationId, + entityId, + labels, + redirectUri, + data, + }, + }) + .then((res) => res.data); + + return new ConnectionRequest({ + connectionStatus: res?.connectionStatus!, + connectedAccountId: res?.connectedAccountId!, + redirectUri: res?.redirectUrl!, + }); + } catch (error) { + throw CEG.handleAllError(error); } + } } export class ConnectionRequest { + connectionStatus: string; + connectedAccountId: string; + redirectUrl: string | null; + + constructor({ + connectionStatus, + connectedAccountId, + redirectUri, + }: { connectionStatus: string; connectedAccountId: string; - redirectUrl: string | null; - - constructor({connectionStatus,connectedAccountId, redirectUri}: {connectionStatus: string,connectedAccountId: string, redirectUri: string | null}) { - this.connectionStatus = connectionStatus; - this.connectedAccountId = connectedAccountId; - this.redirectUrl = redirectUri; - } - - async saveUserAccessData(data: { - fieldInputs: Record; - redirectUrl?: string; - entityId?: string; - }) { - try { - const { data: connectedAccount } = await apiClient.connections.getConnection({ path: { connectedAccountId: this.connectedAccountId } }); - if (!connectedAccount) throw new Error("Connected account not found"); - return await apiClient.connections.initiateConnection({ - body: { - integrationId: connectedAccount.integrationId, - //@ts-ignore - data: data.fieldInputs, - redirectUri: data.redirectUrl, - userUuid: data.entityId, - entityId: data.entityId, - } - }); - } catch (error) { - throw CEG.handleAllError(error); - } + redirectUri: string | null; + }) { + this.connectionStatus = connectionStatus; + this.connectedAccountId = connectedAccountId; + this.redirectUrl = redirectUri; + } + + async saveUserAccessData(data: { + fieldInputs: Record; + redirectUrl?: string; + entityId?: string; + }) { + try { + const { data: connectedAccount } = + await apiClient.connections.getConnection({ + path: { connectedAccountId: this.connectedAccountId }, + }); + if (!connectedAccount) throw new Error("Connected account not found"); + return await apiClient.connections.initiateConnection({ + body: { + integrationId: connectedAccount.integrationId, + //@ts-ignore + data: data.fieldInputs, + redirectUri: data.redirectUrl, + userUuid: data.entityId, + entityId: data.entityId, + }, + }); + } catch (error) { + throw CEG.handleAllError(error); } - - async getAuthInfo(data: GetConnectionInfoData["path"]): Promise { - try { - const res = await client.connections.getConnectionInfo({ path: data }); - return res.data!; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async getAuthInfo( + data: GetConnectionInfoData["path"] + ): Promise { + try { + const res = await client.connections.getConnectionInfo({ path: data }); + return res.data!; + } catch (error) { + throw CEG.handleAllError(error); } - - async waitUntilActive(timeout = 60) { - try { - const startTime = Date.now(); - while (Date.now() - startTime < timeout * 1000) { - const connection = await apiClient.connections.getConnection({ path: { connectedAccountId: this.connectedAccountId } }).then(res => res.data); - if (!connection) throw new Error("Connected account not found"); - if (connection.status === 'ACTIVE') { - return connection; - } - await new Promise(resolve => setTimeout(resolve, 1000)); - } - throw new Error('Connection did not become active within the timeout period.'); - } catch (error) { - throw CEG.handleAllError(error); + } + + async waitUntilActive(timeout = 60) { + try { + const startTime = Date.now(); + while (Date.now() - startTime < timeout * 1000) { + const connection = await apiClient.connections + .getConnection({ + path: { connectedAccountId: this.connectedAccountId }, + }) + .then((res) => res.data); + if (!connection) throw new Error("Connected account not found"); + if (connection.status === "ACTIVE") { + return connection; } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + throw new Error( + "Connection did not become active within the timeout period." + ); + } catch (error) { + throw CEG.handleAllError(error); } + } } diff --git a/js/src/sdk/models/integrations.spec.ts b/js/src/sdk/models/integrations.spec.ts index cd9d957da7..d64e11eaf4 100644 --- a/js/src/sdk/models/integrations.spec.ts +++ b/js/src/sdk/models/integrations.spec.ts @@ -3,57 +3,58 @@ import { getBackendClient } from "../testUtils/getBackendClient"; import { Integrations } from "./integrations"; describe("Integrations class tests", () => { - let backendClient; - let integrations: Integrations; - let createdIntegrationId: string; - - beforeAll(() => { - backendClient = getBackendClient(); - integrations = new Integrations(backendClient); + let backendClient; + let integrations: Integrations; + let createdIntegrationId: string; + + beforeAll(() => { + backendClient = getBackendClient(); + integrations = new Integrations(backendClient); + }); + + it("Retrieve integrations list", async () => { + const integrationsList = await integrations.list(); + expect(integrationsList?.items).toBeInstanceOf(Array); + expect(integrationsList?.items).not.toHaveLength(0); + }); + + it("should create an integration and verify its properties", async () => { + const integrationCreation = await integrations.create({ + appId: "01e22f33-dc3f-46ae-b58d-050e4d2d1909", + name: "test_integration_220", + useComposioAuth: true, + // @ts-ignore + forceNewIntegration: true, }); + expect(integrationCreation.id).toBeTruthy(); + expect(integrationCreation.appName).toBe("github"); - it("Retrieve integrations list", async () => { - const integrationsList = await integrations.list(); - expect(integrationsList?.items).toBeInstanceOf(Array); - expect(integrationsList?.items).not.toHaveLength(0); - }); - - it("should create an integration and verify its properties", async () => { - const integrationCreation = await integrations.create({ - appId: "01e22f33-dc3f-46ae-b58d-050e4d2d1909", - name: "test_integration_220", - useComposioAuth: true, - // @ts-ignore - forceNewIntegration:true - }); - expect(integrationCreation.id).toBeTruthy(); - expect(integrationCreation.appName).toBe("github"); - - // @ts-ignore - createdIntegrationId = integrationCreation.id; - }); - - it("should retrieve the created integration by ID and verify its properties", async () => { - const integration = await integrations.get({ - integrationId: createdIntegrationId - }); - expect(integration?.id).toBe(createdIntegrationId); - expect(integration?.appId).toBe("01e22f33-dc3f-46ae-b58d-050e4d2d1909"); - expect(integration?.authScheme).toBe("OAUTH2"); - expect(integration?.expectedInputFields).toBeDefined(); - }); + // @ts-ignore + createdIntegrationId = integrationCreation.id; + }); - it("should get the required params for the created integration", async () => { - const requiredParams = await integrations.getRequiredParams(createdIntegrationId); - expect(requiredParams).toBeDefined(); + it("should retrieve the created integration by ID and verify its properties", async () => { + const integration = await integrations.get({ + integrationId: createdIntegrationId, }); - - it("should delete the created integration", async () => { - if (!createdIntegrationId) return; - await integrations.delete({ - path:{ - integrationId: createdIntegrationId - } - }); + expect(integration?.id).toBe(createdIntegrationId); + expect(integration?.appId).toBe("01e22f33-dc3f-46ae-b58d-050e4d2d1909"); + expect(integration?.authScheme).toBe("OAUTH2"); + expect(integration?.expectedInputFields).toBeDefined(); + }); + + it("should get the required params for the created integration", async () => { + const requiredParams = + await integrations.getRequiredParams(createdIntegrationId); + expect(requiredParams).toBeDefined(); + }); + + it("should delete the created integration", async () => { + if (!createdIntegrationId) return; + await integrations.delete({ + path: { + integrationId: createdIntegrationId, + }, }); + }); }); diff --git a/js/src/sdk/models/integrations.ts b/js/src/sdk/models/integrations.ts index 41acc077c1..f731c68453 100644 --- a/js/src/sdk/models/integrations.ts +++ b/js/src/sdk/models/integrations.ts @@ -1,189 +1,191 @@ -import { DeleteConnectorData, GetConnectorInfoData, GetConnectorInfoResDTO, GetConnectorListResDTO } from "../client"; -import apiClient from "../client/client" +import { + DeleteConnectorData, + GetConnectorInfoData, + GetConnectorInfoResDTO, + GetConnectorListResDTO, +} from "../client"; +import apiClient from "../client/client"; import { BackendClient } from "./backendClient"; import { CEG } from "../utils/error"; export type ListAllIntegrationsData = { + /** + * Page number to fetch + */ + page?: number; + /** + * Page Size to assume + */ + pageSize?: number; + /** + * The name of the app to filter by + */ + appName?: string; + /** + * Whether to show disabled integrations + */ + showDisabled?: boolean; +}; + +export type GetIntegrationData = { + /** + * The unique identifier of the integration. + */ + integrationId: string; +}; + +export type CreateIntegrationData = { + requestBody?: { /** - * Page number to fetch + * The name of the connector. */ - page?: number; + name?: string; /** - * Page Size to assume + * The authentication scheme used by the connector (e.g., "OAUTH2", "API_KEY"). */ - pageSize?: number; + authScheme?: string; /** - * The name of the app to filter by + * The unique identifier of the app associated with the connector. */ - appName?: string; + appId?: string; + forceNewIntegration?: boolean; /** - * Whether to show disabled integrations + * An object containing the authentication configuration for the connector. */ - showDisabled?: boolean; -}; + authConfig?: { + /** + * The client ID used for authentication with the app - if authScheme is OAUTH2 + */ + client_id?: string; + /** + * The client secret used for authentication with the app - if authScheme is OAUTH2 + */ + client_secret?: string; + /** + * The API key used for authentication with the app - if authScheme is API_KEY + */ + api_key?: string; + /** + * The Consumer key used for authentication with the app - if authScheme is OAUTH1 + */ + consumer_key?: string; + /** + * The Consumer secret used for authentication with the app - if authScheme is OAUTH1 + */ + consumer_secret?: string; + /** + * The base URL for making API requests to the app. + */ + base_url?: string; -export type GetIntegrationData = { + [key: string]: unknown; + }; /** - * The unique identifier of the integration. + * Use default Composio credentials to proceed. The developer app credentials will be of Composio. */ - integrationId: string; + useComposioAuth?: boolean; + }; }; -export type CreateIntegrationData = { - requestBody?: { - /** - * The name of the connector. - */ - name?: string; - /** - * The authentication scheme used by the connector (e.g., "OAUTH2", "API_KEY"). - */ - authScheme?: string; - /** - * The unique identifier of the app associated with the connector. - */ - appId?: string; - forceNewIntegration?: boolean; - /** - * An object containing the authentication configuration for the connector. - */ - authConfig?: { - /** - * The client ID used for authentication with the app - if authScheme is OAUTH2 - */ - client_id?: string; - /** - * The client secret used for authentication with the app - if authScheme is OAUTH2 - */ - client_secret?: string; - /** - * The API key used for authentication with the app - if authScheme is API_KEY - */ - api_key?: string; - /** - * The Consumer key used for authentication with the app - if authScheme is OAUTH1 - */ - consumer_key?: string; - /** - * The Consumer secret used for authentication with the app - if authScheme is OAUTH1 - */ - consumer_secret?: string; - /** - * The base URL for making API requests to the app. - */ - base_url?: string; - - [key: string]: unknown; - }; - /** - * Use default Composio credentials to proceed. The developer app credentials will be of Composio. - */ - useComposioAuth?: boolean; - }; -}; - - export class Integrations { + backendClient: BackendClient; - backendClient: BackendClient; + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + } - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; - } + /** + * Retrieves a list of all available integrations in the Composio platform. + * + * This method allows clients to explore and discover the supported integrations. It returns an array of integration objects, each containing essential details such as the integration's key, name, description, logo, categories, and unique identifier. + * + * @returns {Promise} A promise that resolves to the list of all integrations. + * @throws {ApiError} If the request fails. + */ + async list(data: ListAllIntegrationsData = {}) { + try { + const response = await apiClient.appConnector.listAllConnectors({ + query: data, + }); - /** - * Retrieves a list of all available integrations in the Composio platform. - * - * This method allows clients to explore and discover the supported integrations. It returns an array of integration objects, each containing essential details such as the integration's key, name, description, logo, categories, and unique identifier. - * - * @returns {Promise} A promise that resolves to the list of all integrations. - * @throws {ApiError} If the request fails. - */ - async list(data: ListAllIntegrationsData = {}) { - try { - const response = await apiClient.appConnector.listAllConnectors({ - query: data - }); - - - return response.data - } catch (error) { - throw CEG.handleAllError(error); - } + return response.data; + } catch (error) { + throw CEG.handleAllError(error); } + } - /** - * Retrieves details of a specific integration in the Composio platform by providing its integration name. - * - * The response includes the integration's name, display name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {GetIntegrationData} data The data for the request. - * @returns {Promise} A promise that resolves to the details of the integration. - * @throws {ApiError} If the request fails. - */ - async get(data: GetIntegrationData) { - try { - const response = await apiClient.appConnector.getConnectorInfo({ - path: data - }); - return response.data; - } catch (error) { - throw CEG.handleAllError(error); - } + /** + * Retrieves details of a specific integration in the Composio platform by providing its integration name. + * + * The response includes the integration's name, display name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {GetIntegrationData} data The data for the request. + * @returns {Promise} A promise that resolves to the details of the integration. + * @throws {ApiError} If the request fails. + */ + async get(data: GetIntegrationData) { + try { + const response = await apiClient.appConnector.getConnectorInfo({ + path: data, + }); + return response.data; + } catch (error) { + throw CEG.handleAllError(error); } + } - async getRequiredParams(integrationId: string) { - try { - const response = await apiClient.appConnector.getConnectorInfo({ - path: { - integrationId - }, - throwOnError: true - }); - return response.data?.expectedInputFields; - } catch (error) { - throw CEG.handleAllError(error); - } + async getRequiredParams(integrationId: string) { + try { + const response = await apiClient.appConnector.getConnectorInfo({ + path: { + integrationId, + }, + throwOnError: true, + }); + return response.data?.expectedInputFields; + } catch (error) { + throw CEG.handleAllError(error); } + } - /** - * Creates a new integration in the Composio platform. - * - * This method allows clients to create a new integration by providing the necessary details such as app ID, name, authentication mode, and configuration. - * - * @param {CreateIntegrationData["requestBody"]} data The data for the request. - * @returns {Promise} A promise that resolves to the created integration model. - * @throws {ApiError} If the request fails. - */ - async create(data: CreateIntegrationData["requestBody"]) { - try { - if (!data?.authConfig) { - data!.authConfig = {}; - } + /** + * Creates a new integration in the Composio platform. + * + * This method allows clients to create a new integration by providing the necessary details such as app ID, name, authentication mode, and configuration. + * + * @param {CreateIntegrationData["requestBody"]} data The data for the request. + * @returns {Promise} A promise that resolves to the created integration model. + * @throws {ApiError} If the request fails. + */ + async create(data: CreateIntegrationData["requestBody"]) { + try { + if (!data?.authConfig) { + data!.authConfig = {}; + } - const response = await apiClient.appConnector.createConnector({ - body: { - name: data?.name!, - appId: data?.appId!, - authConfig: data?.authConfig! as any, - authScheme: data?.authScheme, - useComposioAuth: data?.useComposioAuth!, - forceNewIntegration: true - }, - throwOnError: true - }); - return response.data; - } catch (error) { - throw CEG.handleAllError(error); - } + const response = await apiClient.appConnector.createConnector({ + body: { + name: data?.name!, + appId: data?.appId!, + authConfig: data?.authConfig! as any, + authScheme: data?.authScheme, + useComposioAuth: data?.useComposioAuth!, + forceNewIntegration: true, + }, + throwOnError: true, + }); + return response.data; + } catch (error) { + throw CEG.handleAllError(error); } + } - async delete(data: DeleteConnectorData) { - try { - const response = await apiClient.appConnector.deleteConnector(data); - return response.data; - } catch (error) { - throw CEG.handleAllError(error); - } - } + async delete(data: DeleteConnectorData) { + try { + const response = await apiClient.appConnector.deleteConnector(data); + return response.data; + } catch (error) { + throw CEG.handleAllError(error); + } + } } diff --git a/js/src/sdk/models/triggers.spec.ts b/js/src/sdk/models/triggers.spec.ts index 413ed8b870..1ebbb1fb59 100644 --- a/js/src/sdk/models/triggers.spec.ts +++ b/js/src/sdk/models/triggers.spec.ts @@ -7,128 +7,130 @@ import { Entity } from "./Entity"; import { Actions } from "./actions"; describe("Apps class tests", () => { - let backendClient; - let triggers: Triggers; - let connectedAccounts: ConnectedAccounts; - let entity: Entity; - - let triggerId: string; - let actions: Actions; - - beforeAll(() => { - backendClient = getBackendClient(); - triggers = new Triggers(backendClient); - connectedAccounts = new ConnectedAccounts(backendClient); - entity = new Entity(backendClient, "default"); - connectedAccounts = new ConnectedAccounts(backendClient); - actions = new Actions(backendClient); + let backendClient; + let triggers: Triggers; + let connectedAccounts: ConnectedAccounts; + let entity: Entity; + + let triggerId: string; + let actions: Actions; + + beforeAll(() => { + backendClient = getBackendClient(); + triggers = new Triggers(backendClient); + connectedAccounts = new ConnectedAccounts(backendClient); + entity = new Entity(backendClient, "default"); + connectedAccounts = new ConnectedAccounts(backendClient); + actions = new Actions(backendClient); + }); + + it("should create an Apps instance and retrieve apps list", async () => { + const triggerList = await triggers.list(); + expect(triggerList.length).toBeGreaterThan(0); + }); + + it("should retrieve a list of triggers for a specific app", async () => { + const triggerList = await triggers.list({ + appNames: "github", }); - - it("should create an Apps instance and retrieve apps list", async () => { - const triggerList = await triggers.list(); - expect(triggerList.length).toBeGreaterThan(0); - }); - - it("should retrieve a list of triggers for a specific app", async () => { - const triggerList = await triggers.list({ - appNames: "github" - }); - // this is breaking for now - expect(triggerList.length).toBeGreaterThan(0); - expect(triggerList[0].appName).toBe("github"); - }); - - + // this is breaking for now + expect(triggerList.length).toBeGreaterThan(0); + expect(triggerList[0].appName).toBe("github"); + }); }); - describe("Apps class tests subscribe", () => { - let backendClient; - let triggers: Triggers; - let connectedAccounts: ConnectedAccounts; - let actions: Actions; - let entity: Entity; - - let triggerId: string; - - beforeAll(() => { - backendClient = getBackendClient(); - triggers = new Triggers(backendClient); - connectedAccounts = new ConnectedAccounts(backendClient); - entity = new Entity(backendClient, "default"); - actions = new Actions(backendClient); + let backendClient; + let triggers: Triggers; + let connectedAccounts: ConnectedAccounts; + let actions: Actions; + let entity: Entity; + + let triggerId: string; + + beforeAll(() => { + backendClient = getBackendClient(); + triggers = new Triggers(backendClient); + connectedAccounts = new ConnectedAccounts(backendClient); + entity = new Entity(backendClient, "default"); + actions = new Actions(backendClient); + }); + + it("should create a new trigger for gmail", async () => { + const connectedAccount = await connectedAccounts.list({ + user_uuid: "default", }); - - - it("should create a new trigger for gmail", async () => { - const connectedAccount = await connectedAccounts.list({ user_uuid: 'default' }); - - const connectedAccountId = connectedAccount.items.find(item => item.appName === 'gmail')?.id; - if(!connectedAccountId) { - throw new Error("No connected account found"); - } - const trigger = await triggers.setup({connectedAccountId, triggerName: 'gmail_new_gmail_message', config: { - "userId": connectedAccount.items[0].id, - "interval": 60, - "labelIds": "INBOX", - }}); - - expect(trigger.status).toBe("success"); - expect(trigger.triggerId).toBeTruthy(); - - triggerId = trigger.triggerId; - }) - - it("should disable, enable, and then disable the created trigger", async () => { - let trigger = await triggers.disable({ triggerId }); - expect(trigger.status).toBe("success"); - - trigger = await triggers.enable({ triggerId }); - expect(trigger.status).toBe("success"); - - trigger = await triggers.disable({ triggerId }); - expect(trigger.status).toBe("success"); + const connectedAccountId = connectedAccount.items.find( + (item) => item.appName === "gmail" + )?.id; + if (!connectedAccountId) { + throw new Error("No connected account found"); + } + const trigger = await triggers.setup({ + connectedAccountId, + triggerName: "gmail_new_gmail_message", + config: { + userId: connectedAccount.items[0].id, + interval: 60, + labelIds: "INBOX", + }, }); - // it("should subscribe to a trigger and receive a trigger", async () => { - // function waitForTriggerReceived() { - // return new Promise((resolve) => { - // triggers.subscribe((data) => { - // resolve(data); - // }, { - // appName: "github", - // triggerName: "GITHUB_ISSUE_ADDED_EVENT" - // }); - - // setTimeout(async () => { - // const actionName = "github_create_an_issue"; - // // Not urgent - // const connectedAccountsResult = await connectedAccounts.list({ integrationId: 'ca85b86b-1198-4e1a-8d84-b14640564c77' }); - // const connectionId = connectedAccountsResult.items[0].id; - - // await actions.execute({ - // actionName, - // requestBody: { - // connectedAccountId: connectionId, - // input: { - // title: "test", - // owner: "ComposioHQ", - // repo: "test_repo", - // }, - // appName: 'github' - // } - // }); - // }, 4000); - // }); - // } - - // const data = await waitForTriggerReceived(); - - // //@ts-ignore - // expect(data.payload.triggerName).toBe("GITHUB_ISSUE_ADDED_EVENT"); - - // triggers.unsubscribe(); - // }); - + expect(trigger.status).toBe("success"); + expect(trigger.triggerId).toBeTruthy(); + + triggerId = trigger.triggerId; + }); + + it("should disable, enable, and then disable the created trigger", async () => { + let trigger = await triggers.disable({ triggerId }); + expect(trigger.status).toBe("success"); + + trigger = await triggers.enable({ triggerId }); + expect(trigger.status).toBe("success"); + + trigger = await triggers.disable({ triggerId }); + expect(trigger.status).toBe("success"); + }); + + // it("should subscribe to a trigger and receive a trigger", async () => { + // function waitForTriggerReceived() { + // return new Promise((resolve) => { + // triggers.subscribe((data) => { + // resolve(data); + // }, { + // appName: "github", + // triggerName: "GITHUB_ISSUE_ADDED_EVENT" + // }); + + // setTimeout(async () => { + // const actionName = "github_create_an_issue"; + // // Not urgent + // const connectedAccountsResult = await connectedAccounts.list({ integrationId: 'ca85b86b-1198-4e1a-8d84-b14640564c77' }); + // const connectionId = connectedAccountsResult.items[0].id; + + // await actions.execute({ + // actionName, + // requestBody: { + // connectedAccountId: connectionId, + // input: { + // title: "test", + // owner: "ComposioHQ", + // repo: "test_repo", + // }, + // appName: 'github' + // } + // }); + // }, 4000); + // }); + // } + + // const data = await waitForTriggerReceived(); + + // //@ts-ignore + // expect(data.payload.triggerName).toBe("GITHUB_ISSUE_ADDED_EVENT"); + + // triggers.unsubscribe(); + // }); }); diff --git a/js/src/sdk/models/triggers.ts b/js/src/sdk/models/triggers.ts index 857c67582e..25599b36f5 100644 --- a/js/src/sdk/models/triggers.ts +++ b/js/src/sdk/models/triggers.ts @@ -1,9 +1,8 @@ - import { TriggerData, PusherUtils } from "../utils/pusher"; import logger from "../../utils/logger"; -import {BackendClient} from "./backendClient" +import { BackendClient } from "./backendClient"; -import apiClient from "../client/client" +import apiClient from "../client/client"; import { CEG } from "../utils/error"; import { ListTriggersData } from "../client"; @@ -11,146 +10,169 @@ import { ListTriggersData } from "../client"; type RequiredQuery = ListTriggersData["query"]; export class Triggers { - trigger_to_client_event = "trigger_to_client"; - - backendClient: BackendClient; - constructor(backendClient: BackendClient) { - this.backendClient = backendClient; - } - - /** - * Retrieves a list of all triggers in the Composio platform. - * - * This method allows you to fetch a list of all the available triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status. - * - * @param {ListTriggersData} data The data for the request. - * @returns {CancelablePromise} A promise that resolves to the list of all triggers. - * @throws {ApiError} If the request fails. - */ - async list(data: RequiredQuery={} ) { - try { - const {data:response} = await apiClient.triggers.listTriggers({ - query: { - appNames: data?.appNames, - } - }); - return response || []; - } catch (error) { - throw CEG.handleAllError(error); - } + trigger_to_client_event = "trigger_to_client"; + + backendClient: BackendClient; + constructor(backendClient: BackendClient) { + this.backendClient = backendClient; + } + + /** + * Retrieves a list of all triggers in the Composio platform. + * + * This method allows you to fetch a list of all the available triggers. It supports pagination to handle large numbers of triggers. The response includes an array of trigger objects, each containing information such as the trigger's name, description, input parameters, expected response, associated app information, and enabled status. + * + * @param {ListTriggersData} data The data for the request. + * @returns {CancelablePromise} A promise that resolves to the list of all triggers. + * @throws {ApiError} If the request fails. + */ + async list(data: RequiredQuery = {}) { + try { + const { data: response } = await apiClient.triggers.listTriggers({ + query: { + appNames: data?.appNames, + }, + }); + return response || []; + } catch (error) { + throw CEG.handleAllError(error); } - - /** - * Setup a trigger for a connected account. - * - * @param {SetupTriggerData} data The data for the request. - * @returns {CancelablePromise} A promise that resolves to the setup trigger response. - * @throws {ApiError} If the request fails. - */ - async setup({connectedAccountId, triggerName, config}: {connectedAccountId: string, triggerName: string, config: Record}): Promise<{status: string, triggerId: string}> { - try { - const response = await apiClient.triggers.enableTrigger({ - path: { - connectedAccountId, - triggerName - }, - body: { - triggerConfig: config - } - }); - return response.data as {status: string, triggerId: string}; - } catch (error) { - throw CEG.handleAllError(error); - } + } + + /** + * Setup a trigger for a connected account. + * + * @param {SetupTriggerData} data The data for the request. + * @returns {CancelablePromise} A promise that resolves to the setup trigger response. + * @throws {ApiError} If the request fails. + */ + async setup({ + connectedAccountId, + triggerName, + config, + }: { + connectedAccountId: string; + triggerName: string; + config: Record; + }): Promise<{ status: string; triggerId: string }> { + try { + const response = await apiClient.triggers.enableTrigger({ + path: { + connectedAccountId, + triggerName, + }, + body: { + triggerConfig: config, + }, + }); + return response.data as { status: string; triggerId: string }; + } catch (error) { + throw CEG.handleAllError(error); } - - async enable(data: { triggerId: string }) { - try { - const response = await apiClient.triggers.switchTriggerInstanceStatus({ - path: data, - body: { - enabled: true - } - }); - return { - status: "success" - } - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async enable(data: { triggerId: string }) { + try { + const response = await apiClient.triggers.switchTriggerInstanceStatus({ + path: data, + body: { + enabled: true, + }, + }); + return { + status: "success", + }; + } catch (error) { + throw CEG.handleAllError(error); } - - async disable(data: { triggerId: string }) { - try { - const response = await apiClient.triggers.switchTriggerInstanceStatus({ - path: data, - body: { - enabled: false - } - }); - return { - status: "success" - } - } catch (error) { - throw CEG.handleAllError(error); - } + } + + async disable(data: { triggerId: string }) { + try { + const response = await apiClient.triggers.switchTriggerInstanceStatus({ + path: data, + body: { + enabled: false, + }, + }); + return { + status: "success", + }; + } catch (error) { + throw CEG.handleAllError(error); } - - async delete(data: { triggerInstanceId: string }) { - try { - const response = await apiClient.triggers.deleteTrigger({ - path: data - }); - return { - status: "success" - } - } catch (error) { - throw CEG.handleAllError(error); - } - } - - async subscribe(fn: (data: TriggerData) => void, filters:{ - appName?: string, - triggerId? : string; - connectionId?: string; - integrationId?: string; - triggerName?: string; - triggerData?: string; - entityId?: string; - }={}) { - - if(!fn) throw new Error("Function is required for trigger subscription"); - //@ts-ignore - const clientId = await this.backendClient.getClientId(); - //@ts-ignore - await PusherUtils.getPusherClient(this.backendClient.baseUrl, this.backendClient.apiKey); - - const shouldSendTrigger = (data: TriggerData) => { - if(Object.keys(filters).length === 0) return true; - else{ - return ( - (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) && - (!filters.triggerId || data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) && - (!filters.connectionId || data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) && - (!filters.triggerName || data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) && - (!filters.entityId || data.metadata.connection.clientUniqueUserId.toLowerCase() === filters.entityId.toLowerCase()) && - (!filters.integrationId || data.metadata.connection.integrationId.toLowerCase() === filters.integrationId.toLowerCase()) - ); - } - } - - logger.debug("Subscribing to triggers",filters) - PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => { - if (shouldSendTrigger(data)) { - fn(data); - } - }); - } - - async unsubscribe() { - //@ts-ignore - const clientId = await this.backendClient.getClientId(); - PusherUtils.triggerUnsubscribe(clientId); + } + + async delete(data: { triggerInstanceId: string }) { + try { + const response = await apiClient.triggers.deleteTrigger({ + path: data, + }); + return { + status: "success", + }; + } catch (error) { + throw CEG.handleAllError(error); } + } + + async subscribe( + fn: (data: TriggerData) => void, + filters: { + appName?: string; + triggerId?: string; + connectionId?: string; + integrationId?: string; + triggerName?: string; + triggerData?: string; + entityId?: string; + } = {} + ) { + if (!fn) throw new Error("Function is required for trigger subscription"); + //@ts-ignore + const clientId = await this.backendClient.getClientId(); + //@ts-ignore + await PusherUtils.getPusherClient( + this.backendClient.baseUrl, + this.backendClient.apiKey + ); + + const shouldSendTrigger = (data: TriggerData) => { + if (Object.keys(filters).length === 0) return true; + else { + return ( + (!filters.appName || + data.appName.toLowerCase() === filters.appName.toLowerCase()) && + (!filters.triggerId || + data.metadata.id.toLowerCase() === + filters.triggerId.toLowerCase()) && + (!filters.connectionId || + data.metadata.connectionId.toLowerCase() === + filters.connectionId.toLowerCase()) && + (!filters.triggerName || + data.metadata.triggerName.toLowerCase() === + filters.triggerName.toLowerCase()) && + (!filters.entityId || + data.metadata.connection.clientUniqueUserId.toLowerCase() === + filters.entityId.toLowerCase()) && + (!filters.integrationId || + data.metadata.connection.integrationId.toLowerCase() === + filters.integrationId.toLowerCase()) + ); + } + }; + + logger.debug("Subscribing to triggers", filters); + PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => { + if (shouldSendTrigger(data)) { + fn(data); + } + }); + } + + async unsubscribe() { + //@ts-ignore + const clientId = await this.backendClient.getClientId(); + PusherUtils.triggerUnsubscribe(clientId); + } } - diff --git a/js/src/sdk/testUtils/getBackendClient.ts b/js/src/sdk/testUtils/getBackendClient.ts index 959ecdcc96..57aeef71bf 100644 --- a/js/src/sdk/testUtils/getBackendClient.ts +++ b/js/src/sdk/testUtils/getBackendClient.ts @@ -1,16 +1,15 @@ import { BackendClient } from "../models/backendClient"; import { getTestConfig } from "../../../config/getTestConfig"; - export const getBackendClient = (): BackendClient => { - const testConfig = getTestConfig(); - if (testConfig["COMPOSIO_API_KEY"] === undefined) { - throw new Error("COMPOSIO_API_KEY is not set in the test config"); - } - if (testConfig["BACKEND_HERMES_URL"] === undefined) { - throw new Error("BACKEND_HERMES_URL is not set in the test config."); - } - const COMPOSIO_API_KEY = testConfig["COMPOSIO_API_KEY"]; - const BACKEND_HERMES_URL = testConfig["BACKEND_HERMES_URL"]; - return new BackendClient(COMPOSIO_API_KEY, BACKEND_HERMES_URL); -} \ No newline at end of file + const testConfig = getTestConfig(); + if (testConfig["COMPOSIO_API_KEY"] === undefined) { + throw new Error("COMPOSIO_API_KEY is not set in the test config"); + } + if (testConfig["BACKEND_HERMES_URL"] === undefined) { + throw new Error("BACKEND_HERMES_URL is not set in the test config."); + } + const COMPOSIO_API_KEY = testConfig["COMPOSIO_API_KEY"]; + const BACKEND_HERMES_URL = testConfig["BACKEND_HERMES_URL"]; + return new BackendClient(COMPOSIO_API_KEY, BACKEND_HERMES_URL); +}; diff --git a/js/src/sdk/types.d.ts b/js/src/sdk/types.d.ts index 7b21b5794a..642e7bc753 100644 --- a/js/src/sdk/types.d.ts +++ b/js/src/sdk/types.d.ts @@ -3,19 +3,19 @@ export type Dict = { [key: string]: T }; export type Sequence = Array; export type IPythonActionDetails = { - data: { - name: string; - display_name: string; - description: string; - parameters: any; - response: any; - appKey: string; - appId: string; - tags: string[]; - appName: string; - enabled: boolean; - logo: string; - }[]; - error: any | null; - traceback: any | null; -} + data: { + name: string; + display_name: string; + description: string; + parameters: any; + response: any; + appKey: string; + appId: string; + tags: string[]; + appName: string; + enabled: boolean; + logo: string; + }[]; + error: any | null; + traceback: any | null; +}; diff --git a/js/src/sdk/utils.ts b/js/src/sdk/utils.ts index 97a7f57f48..49e3458e6b 100644 --- a/js/src/sdk/utils.ts +++ b/js/src/sdk/utils.ts @@ -2,53 +2,63 @@ import axios from "axios"; import fs from "fs"; export const convertReqParams = (properties: Record) => { - const clonedProperties = JSON.parse(JSON.stringify(properties)); - for (const propertyKey of Object.keys(clonedProperties)) { - const object = clonedProperties[propertyKey]; - const isObject = typeof object === "object"; - const isFile = isObject && (object?.required?.includes("name") && object?.required?.includes("content")); + const clonedProperties = JSON.parse(JSON.stringify(properties)); + for (const propertyKey of Object.keys(clonedProperties)) { + const object = clonedProperties[propertyKey]; + const isObject = typeof object === "object"; + const isFile = + isObject && + object?.required?.includes("name") && + object?.required?.includes("content"); - if (isFile) { - const newKey = `${propertyKey}_file_uri_path`; - clonedProperties[newKey] = { - type: "string", - title: "Name", - description: "Local absolute path to the file or http url to the file" - } + if (isFile) { + const newKey = `${propertyKey}_file_uri_path`; + clonedProperties[newKey] = { + type: "string", + title: "Name", + description: "Local absolute path to the file or http url to the file", + }; - delete clonedProperties[propertyKey]; - } + delete clonedProperties[propertyKey]; } + } + return clonedProperties; +}; - return clonedProperties; -} +export const converReqParamForActionExecution = async ( + params: Record +) => { + const clonedParams = JSON.parse(JSON.stringify(params)); + for (const key of Object.keys(clonedParams)) { + if (key.includes("file_uri_path")) { + const initKey = key.replace("_file_uri_path", ""); + clonedParams[initKey] = {}; + const newKey = clonedParams[initKey]; -export const converReqParamForActionExecution = async (params: Record) => { - const clonedParams = JSON.parse(JSON.stringify(params)); - for (const key of Object.keys(clonedParams)) { - - if (key.includes("file_uri_path")) { - const initKey = key.replace("_file_uri_path", ""); - clonedParams[initKey] = {}; - const newKey = clonedParams[initKey]; - - const valuePassedByClient = clonedParams[key]; - // if not http url - if (valuePassedByClient.startsWith("http") || valuePassedByClient.startsWith("https")) { - newKey.name = valuePassedByClient.split("/").pop(); - const response = await axios.get(valuePassedByClient, { responseType: 'arraybuffer' }); - newKey.content = Buffer.from(response.data, 'binary').toString('base64'); - } else { - const file = await fs.promises.readFile(valuePassedByClient, { - encoding: null - }); - newKey.content = file.toString('base64'); - newKey.name = valuePassedByClient.split("/").pop(); - } - delete clonedParams[key]; - } + const valuePassedByClient = clonedParams[key]; + // if not http url + if ( + valuePassedByClient.startsWith("http") || + valuePassedByClient.startsWith("https") + ) { + newKey.name = valuePassedByClient.split("/").pop(); + const response = await axios.get(valuePassedByClient, { + responseType: "arraybuffer", + }); + newKey.content = Buffer.from(response.data, "binary").toString( + "base64" + ); + } else { + const file = await fs.promises.readFile(valuePassedByClient, { + encoding: null, + }); + newKey.content = file.toString("base64"); + newKey.name = valuePassedByClient.split("/").pop(); + } + delete clonedParams[key]; } + } - return clonedParams; -} \ No newline at end of file + return clonedParams; +}; diff --git a/js/src/sdk/utils/base/batchProcessor.ts b/js/src/sdk/utils/base/batchProcessor.ts index 434bd69322..dfbff43ce3 100644 --- a/js/src/sdk/utils/base/batchProcessor.ts +++ b/js/src/sdk/utils/base/batchProcessor.ts @@ -1,35 +1,38 @@ - export class BatchProcessor { - private batch: unknown[] = []; - private time: number; - private batchSize: number; - private processBatchCallback: (data: unknown[]) => void; - private timer: NodeJS.Timeout | null = null; + private batch: unknown[] = []; + private time: number; + private batchSize: number; + private processBatchCallback: (data: unknown[]) => void; + private timer: NodeJS.Timeout | null = null; - constructor(time: number = 2000, batchSize: number = 100, processBatchCallback: (data: unknown[]) => void) { - this.batch = []; - this.time = time; - this.batchSize = batchSize; - this.processBatchCallback = processBatchCallback; - } + constructor( + time: number = 2000, + batchSize: number = 100, + processBatchCallback: (data: unknown[]) => void + ) { + this.batch = []; + this.time = time; + this.batchSize = batchSize; + this.processBatchCallback = processBatchCallback; + } - pushItem(item: unknown) { - this.batch.push(item); - if (this.batch.length >= this.batchSize) { - this.processBatch(); - } else if (!this.timer) { - this.timer = setTimeout(() => this.processBatch(), this.time); - } + pushItem(item: unknown) { + this.batch.push(item); + if (this.batch.length >= this.batchSize) { + this.processBatch(); + } else if (!this.timer) { + this.timer = setTimeout(() => this.processBatch(), this.time); } + } - processBatch() { - if (this.batch.length > 0) { - this.processBatchCallback(this.batch); - this.batch = []; - } - if (this.timer) { - clearTimeout(this.timer); - this.timer = null; - } + processBatch() { + if (this.batch.length > 0) { + this.processBatchCallback(this.batch); + this.batch = []; + } + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; } -}; \ No newline at end of file + } +} diff --git a/js/src/sdk/utils/cli.ts b/js/src/sdk/utils/cli.ts index bae7503e1c..57b5480c94 100644 --- a/js/src/sdk/utils/cli.ts +++ b/js/src/sdk/utils/cli.ts @@ -6,12 +6,12 @@ import { saveFile } from "./fileUtils"; * @param baseUrl - The base URL to be set in the configuration (optional). */ export function setCliConfig(apiKey: string, baseUrl: string) { - const userData = getUserDataJson(); - userData.api_key = apiKey; - - if (baseUrl) { - userData.base_url = baseUrl; - } - - saveFile(userDataPath(), userData); + const userData = getUserDataJson(); + userData.api_key = apiKey; + + if (baseUrl) { + userData.base_url = baseUrl; + } + + saveFile(userDataPath(), userData); } diff --git a/js/src/sdk/utils/common.ts b/js/src/sdk/utils/common.ts index bf52d588e3..06c1b4d883 100644 --- a/js/src/sdk/utils/common.ts +++ b/js/src/sdk/utils/common.ts @@ -1,4 +1,6 @@ // Helper function to stringify objects if needed -export const serializeValue = (obj: Record | string | number | boolean | null | undefined) => { - return typeof obj === 'object' ? JSON.stringify(obj) : obj; -} +export const serializeValue = ( + obj: Record | string | number | boolean | null | undefined +) => { + return typeof obj === "object" ? JSON.stringify(obj) : obj; +}; diff --git a/js/src/sdk/utils/composioContext.ts b/js/src/sdk/utils/composioContext.ts index c64a0453af..c58068f018 100644 --- a/js/src/sdk/utils/composioContext.ts +++ b/js/src/sdk/utils/composioContext.ts @@ -6,11 +6,11 @@ Warning: Can cause problems if there are multiple instances of the SDK running in the same process. */ class ComposioSDKContext { - static apiKey: string; - static baseURL: string; - static frameworkRuntime?: string; - static source?: string = "javascript"; - static composioVersion?: string; + static apiKey: string; + static baseURL: string; + static frameworkRuntime?: string; + static source?: string = "javascript"; + static composioVersion?: string; } -export default ComposioSDKContext; \ No newline at end of file +export default ComposioSDKContext; diff --git a/js/src/sdk/utils/config.ts b/js/src/sdk/utils/config.ts index 6d15d69a86..e19dd7eedd 100644 --- a/js/src/sdk/utils/config.ts +++ b/js/src/sdk/utils/config.ts @@ -1,112 +1,129 @@ -import * as fs from 'fs'; -import * as path from 'path'; -import * as os from 'os'; -import { LOCAL_CACHE_DIRECTORY_NAME, USER_DATA_FILE_NAME, DEFAULT_BASE_URL } from './constants'; +import * as fs from "fs"; +import * as path from "path"; +import * as os from "os"; +import { + LOCAL_CACHE_DIRECTORY_NAME, + USER_DATA_FILE_NAME, + DEFAULT_BASE_URL, +} from "./constants"; import { getEnvVariable } from "../../utils/shared"; import { client as axiosClient } from "../client/services.gen"; import apiClient from "../client/client"; -import { AxiosInstance } from 'axios'; -import logger from '../../utils/logger'; +import { AxiosInstance } from "axios"; +import logger from "../../utils/logger"; -declare module 'axios' { - export interface InternalAxiosRequestConfig { - metadata?: { - startTime?: number; - }; - } +declare module "axios" { + export interface InternalAxiosRequestConfig { + metadata?: { + startTime?: number; + }; + } } // File path helpers -export const userDataPath = () => path.join(os.homedir(), LOCAL_CACHE_DIRECTORY_NAME, USER_DATA_FILE_NAME); +export const userDataPath = () => + path.join(os.homedir(), LOCAL_CACHE_DIRECTORY_NAME, USER_DATA_FILE_NAME); export const getUserDataJson = () => { - try { - const data = fs.readFileSync(userDataPath(), 'utf8'); - return JSON.parse(data); - } catch (error: any) { - return {}; - } -} + try { + const data = fs.readFileSync(userDataPath(), "utf8"); + return JSON.parse(data); + } catch (error: any) { + return {}; + } +}; // Axios configuration export const setAxiosClientConfig = (axiosClientInstance: AxiosInstance) => { - axiosClientInstance.interceptors.request.use((request) => { - const body = request.data ? JSON.stringify(request.data) : ''; - logger.debug(`API Req [${request.method?.toUpperCase()}] ${request.url}`, { - ...(body && { body }) - }); - request.metadata = { startTime: Date.now() }; - return request; + axiosClientInstance.interceptors.request.use((request) => { + const body = request.data ? JSON.stringify(request.data) : ""; + logger.debug(`API Req [${request.method?.toUpperCase()}] ${request.url}`, { + ...(body && { body }), }); + request.metadata = { startTime: Date.now() }; + return request; + }); - axiosClientInstance.interceptors.response.use( - (response) => { - const method = response.config.method?.toUpperCase(); - const responseSize = Math.round(JSON.stringify(response.data).length / 1024); - const requestStartTime = response.config.metadata?.startTime; - const responseTime = requestStartTime ? Date.now() - requestStartTime : 0; - const responseData = response.data ? JSON.stringify(response.data) : ''; - const status = response.status; + axiosClientInstance.interceptors.response.use( + (response) => { + const method = response.config.method?.toUpperCase(); + const responseSize = Math.round( + JSON.stringify(response.data).length / 1024 + ); + const requestStartTime = response.config.metadata?.startTime; + const responseTime = requestStartTime ? Date.now() - requestStartTime : 0; + const responseData = response.data ? JSON.stringify(response.data) : ""; + const status = response.status; - // @ts-expect-error - response["metadata"] = { - responseTime, - responseSize - } - logger.debug(`API Res [${method}] ${response.config.url} - ${status} - ${responseSize} KB ${responseTime}ms`, { - ...(responseData && { response: JSON.parse(responseData) }) - }); - return response; - }, - (error) => { - const requestStartTime = error.config?.metadata?.startTime; - const responseTime = requestStartTime ? Date.now() - requestStartTime : 0; - const status = error.response?.status || 'Unknown'; - const length = JSON.stringify(error.response?.data)?.length || 0; - const responseSize = Math.round(length / 1024); - - error["metadata"] = { - responseTime, - responseSize - } - logger.debug(`API Error [${status}] ${error.config?.method?.toUpperCase()} ${error.config?.url} - ${status} - ${responseTime}ms`, { - headers: error.response?.headers, - data: error.response?.data, - error: error.message, - responseTime - }); - return Promise.reject(error); + // @ts-expect-error + response["metadata"] = { + responseTime, + responseSize, + }; + logger.debug( + `API Res [${method}] ${response.config.url} - ${status} - ${responseSize} KB ${responseTime}ms`, + { + ...(responseData && { response: JSON.parse(responseData) }), } - ); -} + ); + return response; + }, + (error) => { + const requestStartTime = error.config?.metadata?.startTime; + const responseTime = requestStartTime ? Date.now() - requestStartTime : 0; + const status = error.response?.status || "Unknown"; + const length = JSON.stringify(error.response?.data)?.length || 0; + const responseSize = Math.round(length / 1024); + + error["metadata"] = { + responseTime, + responseSize, + }; + logger.debug( + `API Error [${status}] ${error.config?.method?.toUpperCase()} ${error.config?.url} - ${status} - ${responseTime}ms`, + { + headers: error.response?.headers, + data: error.response?.data, + error: error.message, + responseTime, + } + ); + return Promise.reject(error); + } + ); +}; // Client configuration functions export function getSDKConfig(baseUrl?: string, apiKey?: string) { - const userData = getUserDataJson(); - const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData; + const userData = getUserDataJson(); + const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = + userData; - const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL; - const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || ''; + const baseURLParsed = + baseUrl || + getEnvVariable("COMPOSIO_BASE_URL") || + baseURLFromUserConfig || + DEFAULT_BASE_URL; + const apiKeyParsed = + apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || ""; - return { baseURL: baseURLParsed, apiKey: apiKeyParsed }; + return { baseURL: baseURLParsed, apiKey: apiKeyParsed }; } // Get the API client export function getOpenAPIClient(baseUrl?: string, apiKey?: string) { - const { baseURL, apiKey: apiKeyParsed } = getSDKConfig(baseUrl, apiKey); - - axiosClient.setConfig({ - baseURL, - headers: { - 'X-API-KEY': apiKeyParsed, - 'X-SOURCE': 'js_sdk', - 'X-RUNTIME': 'js_sdk' - }, - throwOnError: true - }); - - setAxiosClientConfig(axiosClient.instance); - return apiClient; -} + const { baseURL, apiKey: apiKeyParsed } = getSDKConfig(baseUrl, apiKey); + axiosClient.setConfig({ + baseURL, + headers: { + "X-API-KEY": apiKeyParsed, + "X-SOURCE": "js_sdk", + "X-RUNTIME": "js_sdk", + }, + throwOnError: true, + }); + setAxiosClientConfig(axiosClient.instance); + return apiClient; +} diff --git a/js/src/sdk/utils/constants.ts b/js/src/sdk/utils/constants.ts index dd9860b2e1..653d2d28dd 100644 --- a/js/src/sdk/utils/constants.ts +++ b/js/src/sdk/utils/constants.ts @@ -1,8 +1,9 @@ // Constants -export const LOCAL_CACHE_DIRECTORY_NAME = '.composio'; -export const USER_DATA_FILE_NAME = 'user_data.json'; +export const LOCAL_CACHE_DIRECTORY_NAME = ".composio"; +export const USER_DATA_FILE_NAME = "user_data.json"; export const DEFAULT_BASE_URL = "https://backend.composio.dev"; -export const TELEMETRY_URL = "https://app.composio.dev" +export const TELEMETRY_URL = "https://app.composio.dev"; -export const IS_DEVELOPMENT_OR_CI = (process.env.DEVELOPMENT || process.env.CI) || false; +export const IS_DEVELOPMENT_OR_CI = + process.env.DEVELOPMENT || process.env.CI || false; diff --git a/js/src/sdk/utils/error.ts b/js/src/sdk/utils/error.ts index 76bcc6e0ba..5bb37f1bdf 100644 --- a/js/src/sdk/utils/error.ts +++ b/js/src/sdk/utils/error.ts @@ -1,160 +1,197 @@ -import { SDK_ERROR_CODES, BASE_ERROR_CODE_INFO, BE_STATUS_CODE_TO_SDK_ERROR_CODES } from "./errors/src/constants"; +import { + SDK_ERROR_CODES, + BASE_ERROR_CODE_INFO, + BE_STATUS_CODE_TO_SDK_ERROR_CODES, +} from "./errors/src/constants"; import { ComposioError } from "./errors/src/composioError"; -import { generateMetadataFromAxiosError, getAPIErrorDetails } from "./errors/src/formatter"; +import { + generateMetadataFromAxiosError, + getAPIErrorDetails, +} from "./errors/src/formatter"; import { AxiosError } from "axios"; import { ZodError } from "zod"; export class CEG { - - static handleAllError(error: unknown, shouldThrow: boolean = false) { - if(error instanceof ComposioError) { - if(shouldThrow) { - throw error; - } - return error; - } - - if (!(error instanceof Error)) { - const error = new Error("Passed error is not an instance of Error"); - if(shouldThrow) { - throw error; - } - return error; - } - - if(error instanceof ZodError) { - const zodError = this.returnZodError(error); - if(shouldThrow) { - throw zodError; - } - return zodError; - } - - const isAxiosError = (error as AxiosError).isAxiosError; - - if (!isAxiosError) { - const customError = this.getCustomError(SDK_ERROR_CODES.COMMON.UNKNOWN, { - message: error.message, - description: "", - possibleFix: "Please check error message and stack trace", - originalError: error, - metadata: {} - }); - if(shouldThrow) { - throw customError; - } - return customError; - } else { - const isResponseNotPresent = !('response' in error); - if(isResponseNotPresent) { - const nonResponseError = this.handleNonResponseAxiosError(error as AxiosError); - if(shouldThrow) { - throw nonResponseError; - } - return nonResponseError; - } - const apiError = this.throwAPIError(error as AxiosError); - if(shouldThrow) { - throw apiError; - } - return apiError; - } + static handleAllError(error: unknown, shouldThrow: boolean = false) { + if (error instanceof ComposioError) { + if (shouldThrow) { + throw error; + } + return error; } - private static handleNonResponseAxiosError(error: AxiosError) { - const fullUrl = (error.config?.baseURL || "") + (error.config?.url || ""); - const metadata = generateMetadataFromAxiosError(error); - - if (error.code === "ECONNREFUSED") { - throw new ComposioError( - SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE, - `ECONNREFUSED for ${fullUrl}`, - "", - "Make sure:\n1. The base URL is correct and is accessible\n2. Your network connection is stable\n3. There are no firewall rules blocking the connection", - metadata, - error - ); - } - - if ( error.code === "ETIMEDOUT") { - throw new ComposioError( - SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT, - `ECONNABORTED for ${fullUrl}`, - `Request to ${fullUrl} timed out after the configured timeout period. This could be due to slow network conditions, server performance issues, or the request being too large. Error code: ECONNABORTED`, - "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", - metadata, - error - ); - } + if (!(error instanceof Error)) { + const error = new Error("Passed error is not an instance of Error"); + if (shouldThrow) { + throw error; + } + return error; + } - if(error.code === "ECONNABORTED") { - throw new ComposioError( - SDK_ERROR_CODES.COMMON.REQUEST_ABORTED, - error.message, - "The request was aborted due to a timeout or other network-related issues. This could be due to network instability, server issues, or the request being too large. Error code: ECONNABORTED", - "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", - metadata, - error - ); - } + if (error instanceof ZodError) { + const zodError = this.returnZodError(error); + if (shouldThrow) { + throw zodError; + } + return zodError; + } - throw new ComposioError( - SDK_ERROR_CODES.COMMON.UNKNOWN, - error.message, - "", - "Please contact tech@composio.dev with the error details.", - metadata, - error + const isAxiosError = (error as AxiosError).isAxiosError; + + if (!isAxiosError) { + const customError = this.getCustomError(SDK_ERROR_CODES.COMMON.UNKNOWN, { + message: error.message, + description: "", + possibleFix: "Please check error message and stack trace", + originalError: error, + metadata: {}, + }); + if (shouldThrow) { + throw customError; + } + return customError; + } else { + const isResponseNotPresent = !("response" in error); + if (isResponseNotPresent) { + const nonResponseError = this.handleNonResponseAxiosError( + error as AxiosError ); + if (shouldThrow) { + throw nonResponseError; + } + return nonResponseError; + } + const apiError = this.throwAPIError(error as AxiosError); + if (shouldThrow) { + throw apiError; + } + return apiError; + } + } + + private static handleNonResponseAxiosError(error: AxiosError) { + const fullUrl = (error.config?.baseURL || "") + (error.config?.url || ""); + const metadata = generateMetadataFromAxiosError(error); + + if (error.code === "ECONNREFUSED") { + throw new ComposioError( + SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE, + `ECONNREFUSED for ${fullUrl}`, + "", + "Make sure:\n1. The base URL is correct and is accessible\n2. Your network connection is stable\n3. There are no firewall rules blocking the connection", + metadata, + error + ); } - static throwAPIError(error: AxiosError) { - const statusCode = error?.response?.status || null; - const errorCode = statusCode ? BE_STATUS_CODE_TO_SDK_ERROR_CODES[statusCode] || SDK_ERROR_CODES.BACKEND.UNKNOWN : SDK_ERROR_CODES.BACKEND.UNKNOWN; - const predefinedError = BASE_ERROR_CODE_INFO[errorCode]; - - const errorDetails = getAPIErrorDetails(errorCode, error, predefinedError); - - const metadata = generateMetadataFromAxiosError(error); - throw new ComposioError(errorCode, errorDetails.message, errorDetails.description, errorDetails.possibleFix, metadata, error) + if (error.code === "ETIMEDOUT") { + throw new ComposioError( + SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT, + `ECONNABORTED for ${fullUrl}`, + `Request to ${fullUrl} timed out after the configured timeout period. This could be due to slow network conditions, server performance issues, or the request being too large. Error code: ECONNABORTED`, + "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", + metadata, + error + ); } - static returnZodError(error: ZodError) { - const errorCode = SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED; - const errorMessage = error.message; - const errorDescription = "The parameters passed are invalid"; - const possibleFix = "Please check the metadata.issues for more details"; - const metadata = { - issues: error.issues - }; - - return new ComposioError(errorCode, errorMessage, errorDescription, possibleFix, metadata, error); + if (error.code === "ECONNABORTED") { + throw new ComposioError( + SDK_ERROR_CODES.COMMON.REQUEST_ABORTED, + error.message, + "The request was aborted due to a timeout or other network-related issues. This could be due to network instability, server issues, or the request being too large. Error code: ECONNABORTED", + "Try:\n1. Checking your network speed and stability\n2. Increasing the request timeout setting if needed\n3. Breaking up large requests into smaller chunks\n4. Retrying the request when network conditions improve\n5. Contact tech@composio.dev if the issue persists", + metadata, + error + ); } - static getCustomError(messageCode: string, { - message, - type, - subtype, - description, - possibleFix, - originalError, - metadata + throw new ComposioError( + SDK_ERROR_CODES.COMMON.UNKNOWN, + error.message, + "", + "Please contact tech@composio.dev with the error details.", + metadata, + error + ); + } + + static throwAPIError(error: AxiosError) { + const statusCode = error?.response?.status || null; + const errorCode = statusCode + ? BE_STATUS_CODE_TO_SDK_ERROR_CODES[statusCode] || + SDK_ERROR_CODES.BACKEND.UNKNOWN + : SDK_ERROR_CODES.BACKEND.UNKNOWN; + const predefinedError = BASE_ERROR_CODE_INFO[errorCode]; + + const errorDetails = getAPIErrorDetails(errorCode, error, predefinedError); + + const metadata = generateMetadataFromAxiosError(error); + throw new ComposioError( + errorCode, + errorDetails.message, + errorDetails.description, + errorDetails.possibleFix, + metadata, + error + ); + } + + static returnZodError(error: ZodError) { + const errorCode = SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED; + const errorMessage = error.message; + const errorDescription = "The parameters passed are invalid"; + const possibleFix = "Please check the metadata.issues for more details"; + const metadata = { + issues: error.issues, + }; + + return new ComposioError( + errorCode, + errorMessage, + errorDescription, + possibleFix, + metadata, + error + ); + } + + static getCustomError( + messageCode: string, + { + message, + type, + subtype, + description, + possibleFix, + originalError, + metadata, }: { - type?: string; - subtype?: string; - message?: string; - description?: string; - possibleFix?: string; - originalError?: unknown; - metadata?: Record; - }): never { - const finalErrorCode = !!messageCode ? messageCode : `${type}::${subtype}`; - const errorDetails = BASE_ERROR_CODE_INFO[finalErrorCode] || BASE_ERROR_CODE_INFO.UNKNOWN; - - const finalMessage = message || errorDetails.message || ""; - const finalDescription = description || errorDetails.description || undefined; - const finalPossibleFix = possibleFix || errorDetails.possibleFix || ""; - - throw new ComposioError(messageCode, finalMessage, finalDescription, finalPossibleFix, metadata, originalError); + type?: string; + subtype?: string; + message?: string; + description?: string; + possibleFix?: string; + originalError?: unknown; + metadata?: Record; } -} \ No newline at end of file + ): never { + const finalErrorCode = !!messageCode ? messageCode : `${type}::${subtype}`; + const errorDetails = + BASE_ERROR_CODE_INFO[finalErrorCode] || BASE_ERROR_CODE_INFO.UNKNOWN; + + const finalMessage = message || errorDetails.message || ""; + const finalDescription = + description || errorDetails.description || undefined; + const finalPossibleFix = possibleFix || errorDetails.possibleFix || ""; + + throw new ComposioError( + messageCode, + finalMessage, + finalDescription, + finalPossibleFix, + metadata, + originalError + ); + } +} diff --git a/js/src/sdk/utils/errors/index.ts b/js/src/sdk/utils/errors/index.ts index 012e4a64bf..395f887ba1 100644 --- a/js/src/sdk/utils/errors/index.ts +++ b/js/src/sdk/utils/errors/index.ts @@ -4,72 +4,73 @@ import { sendBrowserReq, sendProcessReq } from "../../../utils/external"; import { getEnvVariable } from "../../../utils/shared"; type ErrorPayload = { - error_id: string, - error_code: string, - original_error: string, - description: string, - metadata: Record, - message: string, - possible_fix: string, - current_stack: string[], -} + error_id: string; + error_code: string; + original_error: string; + description: string; + metadata: Record; + message: string; + possible_fix: string; + current_stack: string[]; +}; export async function logError(payload: ErrorPayload) { - const isTelementryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true"; - if(isTelementryDisabled) { - return; - } - try { - const isBrowser = typeof window !== 'undefined'; - const reportingPayload = await generateReportingPayload(payload); - const reqPayload = { - data: reportingPayload, - url: `${TELEMETRY_URL}/api/sdk_metrics/error`, - method: "POST", - headers: { - "Content-Type": "application/json" - } - } - - if (isBrowser) { - await sendBrowserReq(reqPayload); - } else { - await sendProcessReq(reqPayload); - } - } catch (error) { - console.error("Error sending error to telemetry", error); - // DO NOTHING + const isTelementryDisabled = + getEnvVariable("TELEMETRY_DISABLED", "false") === "true"; + if (isTelementryDisabled) { + return; + } + try { + const isBrowser = typeof window !== "undefined"; + const reportingPayload = await generateReportingPayload(payload); + const reqPayload = { + data: reportingPayload, + url: `${TELEMETRY_URL}/api/sdk_metrics/error`, + method: "POST", + headers: { + "Content-Type": "application/json", + }, + }; + + if (isBrowser) { + await sendBrowserReq(reqPayload); + } else { + await sendProcessReq(reqPayload); } + } catch (error) { + console.error("Error sending error to telemetry", error); + // DO NOTHING + } } async function generateReportingPayload(payload: ErrorPayload) { + const { apiKey, baseURL, composioVersion, frameworkRuntime, source } = + ComposioSDKContext; + const { + error_id, + error_code, + description, + message, + possible_fix, + original_error, + current_stack, + } = payload; - const { apiKey, baseURL, composioVersion, frameworkRuntime, source } = ComposioSDKContext - const { - error_id, - error_code, - description, - message, - possible_fix, - original_error, - current_stack - } = payload; - - return { - error_id, - error_code, - description, - error_message: message, - possible_fix, - original_error, - current_stack, - sdk_meta: { - platform: process.platform, - version: composioVersion, - baseURL, - apiKey, - frameworkRuntime, - source - } - }; + return { + error_id, + error_code, + description, + error_message: message, + possible_fix, + original_error, + current_stack, + sdk_meta: { + platform: process.platform, + version: composioVersion, + baseURL, + apiKey, + frameworkRuntime, + source, + }, + }; } diff --git a/js/src/sdk/utils/errors/src/composioError.ts b/js/src/sdk/utils/errors/src/composioError.ts index 895dfa193a..75edcdc1f2 100644 --- a/js/src/sdk/utils/errors/src/composioError.ts +++ b/js/src/sdk/utils/errors/src/composioError.ts @@ -1,115 +1,117 @@ -import { v4 as uuidv4 } from 'uuid'; -import { getLogLevel } from '../../../../utils/logger'; -import { logError } from '..'; +import { v4 as uuidv4 } from "uuid"; +import { getLogLevel } from "../../../../utils/logger"; +import { logError } from ".."; /** * Custom error class for Composio that provides rich error details, tracking, and improved debugging */ export class ComposioError extends Error { - // time at which the error occurred - public readonly timestamp: string; - - // unique identifier for the error - private readonly errorId: string; - - // error code - private readonly errCode: string; - - // additional metadata about the error - private readonly metadata?: Record = {}; - - // description of the error - private readonly description?: string; - - // possible fix for the error - private readonly possibleFix?: string; - - // original error object - private readonly _originalError?: any; - - constructor( - errCode: string, - message: string, - description?: string, - possibleFix?: string, - metadata?: Record, - originalError?: any, - ) { - // Ensure message is never empty - super(message || 'An unknown error occurred'); - - // Ensure proper prototype chain for instanceof checks - Object.setPrototypeOf(this, new.target.prototype); - - this.name = 'ComposioError'; - this.errCode = errCode; - this.description = description; - this.possibleFix = possibleFix; - this.timestamp = new Date().toISOString(); - this.metadata = metadata; - this.errorId = uuidv4(); - - let originalErrorString: string = ''; - - // Only print original error if COMPOSIO_LOGGING_LEVEL is debug - if (originalError) { - try { - originalErrorString = typeof originalError === 'object' - ? JSON.parse(JSON.stringify(originalError)) - : originalError; - } catch (e) { - originalErrorString = String(originalError); - } - - if (getLogLevel() === 'debug') { - this._originalError = originalErrorString; - } - } - - logError({ - error_id: this.errorId, - error_code: this.errCode, - original_error: originalErrorString, - description: this.description || '', - metadata: this.metadata || {}, - message: this.message, - possible_fix: this.possibleFix || '', - current_stack: this.stack?.split('\n') || [] - }); - - - // Capture stack trace, excluding constructor call - Error.captureStackTrace(this, this.constructor); - } - - get originalError(): any { - return this._originalError; + // time at which the error occurred + public readonly timestamp: string; + + // unique identifier for the error + private readonly errorId: string; + + // error code + private readonly errCode: string; + + // additional metadata about the error + private readonly metadata?: Record = {}; + + // description of the error + private readonly description?: string; + + // possible fix for the error + private readonly possibleFix?: string; + + // original error object + private readonly _originalError?: any; + + constructor( + errCode: string, + message: string, + description?: string, + possibleFix?: string, + metadata?: Record, + originalError?: any + ) { + // Ensure message is never empty + super(message || "An unknown error occurred"); + + // Ensure proper prototype chain for instanceof checks + Object.setPrototypeOf(this, new.target.prototype); + + this.name = "ComposioError"; + this.errCode = errCode; + this.description = description; + this.possibleFix = possibleFix; + this.timestamp = new Date().toISOString(); + this.metadata = metadata; + this.errorId = uuidv4(); + + let originalErrorString: string = ""; + + // Only print original error if COMPOSIO_LOGGING_LEVEL is debug + if (originalError) { + try { + originalErrorString = + typeof originalError === "object" + ? JSON.parse(JSON.stringify(originalError)) + : originalError; + } catch (e) { + originalErrorString = String(originalError); + } + + if (getLogLevel() === "debug") { + this._originalError = originalErrorString; + } } - - /** - * Returns a complete object representation for logging/serialization - * Includes all error details and metadata - */ - toJSON(): Record { - const errorObj = { - name: this.name, - errorId: this.errorId, - code: this.errCode, - message: this.message, - description: this.description, - possibleFix: this.possibleFix, - timestamp: this.timestamp, - stack: this.stack?.split('\n'), - originalStack: this.originalError?.stack?.split('\n'), - }; - - // Remove undefined/null properties - return Object.entries(errorObj).reduce((acc, [key, value]) => { - if (value !== undefined && value !== null) { - acc[key] = value; - } - return acc; - }, {} as Record); - } -} \ No newline at end of file + logError({ + error_id: this.errorId, + error_code: this.errCode, + original_error: originalErrorString, + description: this.description || "", + metadata: this.metadata || {}, + message: this.message, + possible_fix: this.possibleFix || "", + current_stack: this.stack?.split("\n") || [], + }); + + // Capture stack trace, excluding constructor call + Error.captureStackTrace(this, this.constructor); + } + + get originalError(): any { + return this._originalError; + } + + /** + * Returns a complete object representation for logging/serialization + * Includes all error details and metadata + */ + toJSON(): Record { + const errorObj = { + name: this.name, + errorId: this.errorId, + code: this.errCode, + message: this.message, + description: this.description, + possibleFix: this.possibleFix, + timestamp: this.timestamp, + stack: this.stack?.split("\n"), + originalStack: this.originalError?.stack?.split("\n"), + }; + + // Remove undefined/null properties + return Object.entries(errorObj).reduce( + (acc, [key, value]) => { + if (value !== undefined && value !== null) { + acc[key] = value; + } + return acc; + }, + {} as Record + ); + } +} diff --git a/js/src/sdk/utils/errors/src/constants.ts b/js/src/sdk/utils/errors/src/constants.ts index 7a4b6541ff..42c4641f47 100644 --- a/js/src/sdk/utils/errors/src/constants.ts +++ b/js/src/sdk/utils/errors/src/constants.ts @@ -1,100 +1,105 @@ - -export const SDK_ERROR_CODES = { - BACKEND: { - NOT_FOUND: "BACKEND::NOT_FOUND", - RATE_LIMIT: "BACKEND::RATE_LIMIT", - BAD_REQUEST: "BACKEND::BAD_REQUEST", - UNAUTHORIZED: "BACKEND::UNAUTHORIZED", - SERVER_ERROR: "BACKEND::SERVER_ERROR", - SERVER_UNAVAILABLE: "BACKEND::SERVER_UNAVAILABLE", - UNKNOWN: "BACKEND::UNKNOWN", - }, - COMMON: { - API_KEY_UNAVAILABLE: "COMMON::API_KEY_INVALID", - BASE_URL_NOT_REACHABLE: "COMMON::BASE_URL_NOT_REACHABLE", - UNKNOWN: "COMMON::ERROR_CODE_NOT_DEFINED", - SERVER_UNAVAILABLE: "COMMON::SERVER_UNAVAILABLE", - REQUEST_TIMEOUT: "COMMON::REQUEST_TIMEOUT", - REQUEST_ABORTED: "COMMON::REQUEST_ABORTED", - INVALID_PARAMS_PASSED: "COMMON::INVALID_PARAMS_PASSED", - }, - SDK:{ - NO_CONNECTED_ACCOUNT_FOUND: "SDK::NO_CONNECTED_ACCOUNT_FOUND", - } -} +export const SDK_ERROR_CODES = { + BACKEND: { + NOT_FOUND: "BACKEND::NOT_FOUND", + RATE_LIMIT: "BACKEND::RATE_LIMIT", + BAD_REQUEST: "BACKEND::BAD_REQUEST", + UNAUTHORIZED: "BACKEND::UNAUTHORIZED", + SERVER_ERROR: "BACKEND::SERVER_ERROR", + SERVER_UNAVAILABLE: "BACKEND::SERVER_UNAVAILABLE", + UNKNOWN: "BACKEND::UNKNOWN", + }, + COMMON: { + API_KEY_UNAVAILABLE: "COMMON::API_KEY_INVALID", + BASE_URL_NOT_REACHABLE: "COMMON::BASE_URL_NOT_REACHABLE", + UNKNOWN: "COMMON::ERROR_CODE_NOT_DEFINED", + SERVER_UNAVAILABLE: "COMMON::SERVER_UNAVAILABLE", + REQUEST_TIMEOUT: "COMMON::REQUEST_TIMEOUT", + REQUEST_ABORTED: "COMMON::REQUEST_ABORTED", + INVALID_PARAMS_PASSED: "COMMON::INVALID_PARAMS_PASSED", + }, + SDK: { + NO_CONNECTED_ACCOUNT_FOUND: "SDK::NO_CONNECTED_ACCOUNT_FOUND", + FAILED_TO_INITIATE_CONNECTION: "SDK::FAILED_TO_INITIATE_CONNECTION", + }, +}; export const BASE_ERROR_CODE_INFO = { - [SDK_ERROR_CODES.BACKEND.NOT_FOUND]: { - message: "🔍 API not found", - description: "The requested resource is missing", - possibleFix: "Verify the URL or resource identifier." - }, - [SDK_ERROR_CODES.BACKEND.BAD_REQUEST]: { - message: "🚫 Bad Request. The request was malformed or incorrect", - description: null, - possibleFix: "Please check your request format and parameters." - }, - [SDK_ERROR_CODES.BACKEND.UNAUTHORIZED]: { - message: "🔑 Access Denied", - description: "You do not have the necessary credentials.", - possibleFix: "Ensure your API key is correct and has the required permissions." - }, - [SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT]: { - message: "🕒 Request Timeout", - description: "The request timed out while waiting for a response.", - possibleFix: "Please try again later. If the issue persists, contact support." - }, - [SDK_ERROR_CODES.BACKEND.SERVER_ERROR]: { - message: "💥 Oops! Internal server error", - description: "Your request could not be processed due to an internal server error.", - possibleFix: "Please try again later. If the issue persists, contact support." - }, - [SDK_ERROR_CODES.BACKEND.RATE_LIMIT]: { - message: "⏱️ API Rate Limit Exceeded", - description: "You have exceeded the rate limit for requests.", - possibleFix: "Please wait a bit before trying your request again." - }, - [SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE]: { - message: "🔑 API Key Missing or Invalid", - description: "The API key provided is missing or incorrect.", - possibleFix: "Ensure that your API key is passed to client or set in COMPOSIO_API_KEY environment variable." - }, - [SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE]: { - message: "🚫 Server Unavailable", - description: "The server is currently unable to handle the request.", - possibleFix: "Please try again later. If the issue persists, contact support." - }, - [SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE]: { - message: "🔗 Base URL is not valid", - description: "The base URL provided is not valid.", - possibleFix: "Ensure that the base URL is correct and accessible." - }, - [SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED]: { - message: "🕒 Invalid parameters passed", - description: "The parameters passed are invalid", - possibleFix: "Please check the metadata.issues for more details" - }, - UNKNOWN: { - message: null, - description: null, - possibleFix: "Contact our support team with the error details for further assistance." - }, - [SDK_ERROR_CODES.BACKEND.UNKNOWN]: { - message: null, - description: null, - possibleFix: "Contact our support team with the error details for further assistance." - } -} - + [SDK_ERROR_CODES.BACKEND.NOT_FOUND]: { + message: "🔍 API not found", + description: "The requested resource is missing", + possibleFix: "Verify the URL or resource identifier.", + }, + [SDK_ERROR_CODES.BACKEND.BAD_REQUEST]: { + message: "🚫 Bad Request. The request was malformed or incorrect", + description: null, + possibleFix: "Please check your request format and parameters.", + }, + [SDK_ERROR_CODES.BACKEND.UNAUTHORIZED]: { + message: "🔑 Access Denied", + description: "You do not have the necessary credentials.", + possibleFix: + "Ensure your API key is correct and has the required permissions.", + }, + [SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT]: { + message: "🕒 Request Timeout", + description: "The request timed out while waiting for a response.", + possibleFix: + "Please try again later. If the issue persists, contact support.", + }, + [SDK_ERROR_CODES.BACKEND.SERVER_ERROR]: { + message: "💥 Oops! Internal server error", + description: + "Your request could not be processed due to an internal server error.", + possibleFix: + "Please try again later. If the issue persists, contact support.", + }, + [SDK_ERROR_CODES.BACKEND.RATE_LIMIT]: { + message: "⏱️ API Rate Limit Exceeded", + description: "You have exceeded the rate limit for requests.", + possibleFix: "Please wait a bit before trying your request again.", + }, + [SDK_ERROR_CODES.COMMON.API_KEY_UNAVAILABLE]: { + message: "🔑 API Key Missing or Invalid", + description: "The API key provided is missing or incorrect.", + possibleFix: + "Ensure that your API key is passed to client or set in COMPOSIO_API_KEY environment variable.", + }, + [SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE]: { + message: "🚫 Server Unavailable", + description: "The server is currently unable to handle the request.", + possibleFix: + "Please try again later. If the issue persists, contact support.", + }, + [SDK_ERROR_CODES.COMMON.BASE_URL_NOT_REACHABLE]: { + message: "🔗 Base URL is not valid", + description: "The base URL provided is not valid.", + possibleFix: "Ensure that the base URL is correct and accessible.", + }, + [SDK_ERROR_CODES.COMMON.INVALID_PARAMS_PASSED]: { + message: "🕒 Invalid parameters passed", + description: "The parameters passed are invalid", + possibleFix: "Please check the metadata.issues for more details", + }, + UNKNOWN: { + message: null, + description: null, + possibleFix: + "Contact our support team with the error details for further assistance.", + }, + [SDK_ERROR_CODES.BACKEND.UNKNOWN]: { + message: null, + description: null, + possibleFix: + "Contact our support team with the error details for further assistance.", + }, +}; export const BE_STATUS_CODE_TO_SDK_ERROR_CODES = { - 400: SDK_ERROR_CODES.BACKEND.BAD_REQUEST, - 401: SDK_ERROR_CODES.BACKEND.UNAUTHORIZED, - 404: SDK_ERROR_CODES.BACKEND.NOT_FOUND, - 408: SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT, - 429: SDK_ERROR_CODES.BACKEND.RATE_LIMIT, - 500: SDK_ERROR_CODES.BACKEND.SERVER_ERROR, - 502: SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE, - + 400: SDK_ERROR_CODES.BACKEND.BAD_REQUEST, + 401: SDK_ERROR_CODES.BACKEND.UNAUTHORIZED, + 404: SDK_ERROR_CODES.BACKEND.NOT_FOUND, + 408: SDK_ERROR_CODES.COMMON.REQUEST_TIMEOUT, + 429: SDK_ERROR_CODES.BACKEND.RATE_LIMIT, + 500: SDK_ERROR_CODES.BACKEND.SERVER_ERROR, + 502: SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE, } as Record; - diff --git a/js/src/sdk/utils/errors/src/formatter.ts b/js/src/sdk/utils/errors/src/formatter.ts index f21d0c3021..da3ff578cf 100644 --- a/js/src/sdk/utils/errors/src/formatter.ts +++ b/js/src/sdk/utils/errors/src/formatter.ts @@ -1,86 +1,104 @@ import { ComposioError } from "./composioError"; -import { SDK_ERROR_CODES, BASE_ERROR_CODE_INFO, BE_STATUS_CODE_TO_SDK_ERROR_CODES } from "./constants"; +import { + SDK_ERROR_CODES, + BASE_ERROR_CODE_INFO, + BE_STATUS_CODE_TO_SDK_ERROR_CODES, +} from "./constants"; import { AxiosError } from "axios"; interface ErrorResponse { - errorKey: string; - message: string; - description: string; - possibleFix: string; - metadata?: Record; + errorKey: string; + message: string; + description: string; + possibleFix: string; + metadata?: Record; } interface ErrorDetails { - message: string; - description: string; - possibleFix: string; - metadata?: Record; + message: string; + description: string; + possibleFix: string; + metadata?: Record; } +export const getAPIErrorDetails = ( + errorKey: string, + axiosError: any, + predefinedError: any +): ErrorDetails => { + const defaultErrorDetails = { + message: axiosError.message, + description: + axiosError.response?.data?.message || + axiosError.response?.data?.error || + axiosError.message, + possibleFix: + "Please check the network connection, request parameters, and ensure the API endpoint is correct.", + }; -export const getAPIErrorDetails = (errorKey: string, axiosError: any, predefinedError: any): ErrorDetails => { - const defaultErrorDetails = { - message: axiosError.message, - description: axiosError.response?.data?.message || axiosError.response?.data?.error || axiosError.message, - possibleFix: "Please check the network connection, request parameters, and ensure the API endpoint is correct." - }; + const metadata = generateMetadataFromAxiosError(axiosError); + switch (errorKey) { + case SDK_ERROR_CODES.BACKEND.NOT_FOUND: + case SDK_ERROR_CODES.BACKEND.UNAUTHORIZED: + case SDK_ERROR_CODES.BACKEND.SERVER_ERROR: + case SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE: + case SDK_ERROR_CODES.BACKEND.RATE_LIMIT: + return { + message: `${predefinedError.message || axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, + description: + axiosError.response?.data?.message || predefinedError.description, + possibleFix: + predefinedError.possibleFix || defaultErrorDetails.possibleFix, + metadata, + }; - const metadata = generateMetadataFromAxiosError(axiosError); - switch (errorKey) { - case SDK_ERROR_CODES.BACKEND.NOT_FOUND: - case SDK_ERROR_CODES.BACKEND.UNAUTHORIZED: - case SDK_ERROR_CODES.BACKEND.SERVER_ERROR: - case SDK_ERROR_CODES.BACKEND.SERVER_UNAVAILABLE: - case SDK_ERROR_CODES.BACKEND.RATE_LIMIT: - return { - message: `${predefinedError.message || axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, - description: axiosError.response?.data?.message || predefinedError.description, - possibleFix: predefinedError.possibleFix || defaultErrorDetails.possibleFix, - metadata - }; + case SDK_ERROR_CODES.BACKEND.BAD_REQUEST: + const validationErrors = axiosError.response?.data?.errors; + const formattedErrors = Array.isArray(validationErrors) + ? validationErrors.map((err) => JSON.stringify(err)).join(", ") + : JSON.stringify(validationErrors); - case SDK_ERROR_CODES.BACKEND.BAD_REQUEST: - const validationErrors = axiosError.response?.data?.errors; - const formattedErrors = Array.isArray(validationErrors) - ? validationErrors.map(err => JSON.stringify(err)).join(", ") - : JSON.stringify(validationErrors); + return { + message: `Validation Errors while making request to ${axiosError.config.baseURL + axiosError.config.url}`, + description: `Validation Errors: ${formattedErrors}`, + possibleFix: + "Please check the request parameters and ensure they are correct.", + metadata, + }; - return { - message: `Validation Errors while making request to ${axiosError.config.baseURL + axiosError.config.url}`, - description: `Validation Errors: ${formattedErrors}`, - possibleFix: "Please check the request parameters and ensure they are correct.", - metadata - }; + case SDK_ERROR_CODES.BACKEND.UNKNOWN: + case SDK_ERROR_CODES.COMMON.UNKNOWN: + return { + message: `${axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, + description: + axiosError.response?.data?.message || + axiosError.response?.data?.error || + axiosError.message, + possibleFix: "Please contact tech@composio.dev with the error details.", + metadata, + }; - case SDK_ERROR_CODES.BACKEND.UNKNOWN: - case SDK_ERROR_CODES.COMMON.UNKNOWN: - return { - message: `${axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, - description: axiosError.response?.data?.message || axiosError.response?.data?.error || axiosError.message, - possibleFix: "Please contact tech@composio.dev with the error details.", - metadata - }; - - default: - return { - message: `${predefinedError.message || axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, - description: axiosError.response?.data?.message || predefinedError.description, - possibleFix: predefinedError.possibleFix || defaultErrorDetails.possibleFix, - metadata - }; - } + default: + return { + message: `${predefinedError.message || axiosError.message} for ${axiosError.config.baseURL + axiosError.config.url}`, + description: + axiosError.response?.data?.message || predefinedError.description, + possibleFix: + predefinedError.possibleFix || defaultErrorDetails.possibleFix, + metadata, + }; + } }; - -export const generateMetadataFromAxiosError = (axiosError: any): Record => { - const requestId = axiosError.response?.headers["x-request-id"]; - return { - fullUrl: axiosError.config.baseURL + axiosError.config.url, - method: axiosError.config.method.toUpperCase(), - statusCode: axiosError.response?.status, - requestId: requestId ? `Request ID: ${requestId}` : undefined, - metadata: axiosError.metadata, - } -} - - +export const generateMetadataFromAxiosError = ( + axiosError: any +): Record => { + const requestId = axiosError.response?.headers["x-request-id"]; + return { + fullUrl: axiosError.config.baseURL + axiosError.config.url, + method: axiosError.config.method.toUpperCase(), + statusCode: axiosError.response?.status, + requestId: requestId ? `Request ID: ${requestId}` : undefined, + metadata: axiosError.metadata, + }; +}; diff --git a/js/src/sdk/utils/fileUtils.ts b/js/src/sdk/utils/fileUtils.ts index a9bab233d3..a9ab452fcc 100644 --- a/js/src/sdk/utils/fileUtils.ts +++ b/js/src/sdk/utils/fileUtils.ts @@ -1,28 +1,28 @@ -import * as path from 'path'; -import * as os from 'os'; +import * as path from "path"; +import * as os from "os"; -import * as fs from 'fs'; +import * as fs from "fs"; export const getComposioDir = () => { - const composioDir = path.join(os.homedir(), '.composio'); - if (!fs.existsSync(composioDir)) { - fs.mkdirSync(composioDir, { recursive: true }); - } - return composioDir; -} + const composioDir = path.join(os.homedir(), ".composio"); + if (!fs.existsSync(composioDir)) { + fs.mkdirSync(composioDir, { recursive: true }); + } + return composioDir; +}; export const getComposioFilesDir = () => { - const composioFilesDir = path.join(os.homedir(), '.composio', 'files'); - if (!fs.existsSync(composioFilesDir)) { - fs.mkdirSync(composioFilesDir, { recursive: true }); - } - return composioFilesDir; -} + const composioFilesDir = path.join(os.homedir(), ".composio", "files"); + if (!fs.existsSync(composioFilesDir)) { + fs.mkdirSync(composioFilesDir, { recursive: true }); + } + return composioFilesDir; +}; export const saveFile = (file: string, content: string) => { - const composioFilesDir = getComposioFilesDir(); - const filePath = `${composioFilesDir}/${file}`; - fs.writeFileSync(filePath, content); + const composioFilesDir = getComposioFilesDir(); + const filePath = `${composioFilesDir}/${file}`; + fs.writeFileSync(filePath, content); - return filePath; -} \ No newline at end of file + return filePath; +}; diff --git a/js/src/sdk/utils/other.ts b/js/src/sdk/utils/other.ts index 41381065ab..17e7061a75 100644 --- a/js/src/sdk/utils/other.ts +++ b/js/src/sdk/utils/other.ts @@ -1,9 +1,9 @@ -export const isNewerVersion = (v1: string, v2: string): boolean => { - const parts1 = v1.split('.').map(Number); - const parts2 = v2.split('.').map(Number); - for (let i = 0; i < 3; i++) { - if (parts1[i] > parts2[i]) return true; - if (parts1[i] < parts2[i]) return false; - } - return false; -} \ No newline at end of file +export const isNewerVersion = (v1: string, v2: string): boolean => { + const parts1 = v1.split(".").map(Number); + const parts2 = v2.split(".").map(Number); + for (let i = 0; i < 3; i++) { + if (parts1[i] > parts2[i]) return true; + if (parts1[i] < parts2[i]) return false; + } + return false; +}; diff --git a/js/src/sdk/utils/projectUtils.ts b/js/src/sdk/utils/projectUtils.ts index e573896d9e..2d19c628be 100644 --- a/js/src/sdk/utils/projectUtils.ts +++ b/js/src/sdk/utils/projectUtils.ts @@ -1,22 +1,22 @@ -import * as path from 'path'; -import * as fs from 'fs'; +import * as path from "path"; +import * as fs from "fs"; /** * Finds the directory containing the package.json file by traversing up the directory tree. * @returns {string | null} The absolute path to the directory containing package.json, or null if not found. */ export function getPackageJsonDir(): string | null { - let currentDir = __dirname; - - while (currentDir !== path.parse(currentDir).root) { - const packageJsonPath = path.join(currentDir, 'package.json'); - - if (fs.existsSync(packageJsonPath)) { - return currentDir; - } - - currentDir = path.dirname(currentDir); + let currentDir = __dirname; + + while (currentDir !== path.parse(currentDir).root) { + const packageJsonPath = path.join(currentDir, "package.json"); + + if (fs.existsSync(packageJsonPath)) { + return currentDir; } - - return null; + + currentDir = path.dirname(currentDir); + } + + return null; } diff --git a/js/src/sdk/utils/pusher.ts b/js/src/sdk/utils/pusher.ts index 17f524c16e..c1fc9d332d 100644 --- a/js/src/sdk/utils/pusher.ts +++ b/js/src/sdk/utils/pusher.ts @@ -1,115 +1,136 @@ import logger from "../../utils/logger"; -const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152" -const PUSHER_CLUSTER = "mt1" +const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152"; +const PUSHER_CLUSTER = "mt1"; type PusherClient = any; export interface TriggerData { - appName: string; - clientId: number; - payload: {}; - originalPayload: Record; - metadata: { - id: string; - connectionId: string; - triggerName: string; - triggerData: string; - triggerConfig: Record; - connection: { - id: string; - integrationId: string; - clientUniqueUserId: string; - status: string; - } - } + appName: string; + clientId: number; + payload: {}; + originalPayload: Record; + metadata: { + id: string; + connectionId: string; + triggerName: string; + triggerData: string; + triggerConfig: Record; + connection: { + id: string; + integrationId: string; + clientUniqueUserId: string; + status: string; + }; + }; } - export class PusherUtils { + static pusherClient: PusherClient; - static pusherClient: PusherClient; - - static getPusherClient(baseURL: string, apiKey: string): PusherClient { - - if (!PusherUtils.pusherClient) { - const PusherClient = require("pusher-js") - PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, { - cluster: PUSHER_CLUSTER, - channelAuthorization: { - endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`, - headers: { - "x-api-key": apiKey - }, - transport: "ajax", - } - }); - - } - return PusherUtils.pusherClient; + static getPusherClient(baseURL: string, apiKey: string): PusherClient { + if (!PusherUtils.pusherClient) { + const PusherClient = require("pusher-js"); + PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, { + cluster: PUSHER_CLUSTER, + channelAuthorization: { + endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`, + headers: { + "x-api-key": apiKey, + }, + transport: "ajax", + }, + }); } - /** - * Subscribes to a Pusher channel and binds an event to a callback function. - * @param {string} channelName - The name of the channel to subscribe to. - * @param {string} event - The event to bind to the channel. - * @param {(data: any) => void} fn - The callback function to execute when the event is triggered. - * @returns {PusherClient} The Pusher client instance. - */ - static async subscribe(channelName: string, event: string, fn: (data: any) => void): Promise { - try { - await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn); - } catch (error) { - logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`); - } + return PusherUtils.pusherClient; + } + /** + * Subscribes to a Pusher channel and binds an event to a callback function. + * @param {string} channelName - The name of the channel to subscribe to. + * @param {string} event - The event to bind to the channel. + * @param {(data: any) => void} fn - The callback function to execute when the event is triggered. + * @returns {PusherClient} The Pusher client instance. + */ + static async subscribe( + channelName: string, + event: string, + fn: (data: any) => void + ): Promise { + try { + await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn); + } catch (error) { + logger.error( + `Error subscribing to ${channelName} with event ${event}: ${error}` + ); } + } - /** - * Unsubscribes from a Pusher channel. - * @param {string} channelName - The name of the channel to unsubscribe from. - * @returns {void} - */ - static async unsubscribe(channelName: string): Promise { - PusherUtils.pusherClient.unsubscribe(channelName); - } + /** + * Unsubscribes from a Pusher channel. + * @param {string} channelName - The name of the channel to unsubscribe from. + * @returns {void} + */ + static async unsubscribe(channelName: string): Promise { + PusherUtils.pusherClient.unsubscribe(channelName); + } - /** - * Binds an event to a channel with support for chunked messages. - * @param {PusherClient} channel - The Pusher channel to bind the event to. - * @param {string} event - The event to bind to the channel. - * @param {(data: any) => void} callback - The callback function to execute when the event is triggered. - */ - private static bindWithChunking(channel: PusherClient, event: string, callback: (data: any) => void): void { - channel.bind(event, callback); // Allow normal unchunked events. + /** + * Binds an event to a channel with support for chunked messages. + * @param {PusherClient} channel - The Pusher channel to bind the event to. + * @param {string} event - The event to bind to the channel. + * @param {(data: any) => void} callback - The callback function to execute when the event is triggered. + */ + private static bindWithChunking( + channel: PusherClient, + event: string, + callback: (data: any) => void + ): void { + channel.bind(event, callback); // Allow normal unchunked events. - // Now the chunked variation. Allows arbitrarily long messages. - const events: { [key: string]: { chunks: string[], receivedFinal: boolean } } = {}; - channel.bind("chunked-" + event, (data: { id: string, index: number, chunk: string, final: boolean }) => { - if (!events.hasOwnProperty(data.id)) { - events[data.id] = { chunks: [], receivedFinal: false }; - } - const ev = events[data.id]; - ev.chunks[data.index] = data.chunk; - if (data.final) ev.receivedFinal = true; - if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) { - callback(JSON.parse(ev.chunks.join(""))); - delete events[data.id]; - } - }); - } + // Now the chunked variation. Allows arbitrarily long messages. + const events: { + [key: string]: { chunks: string[]; receivedFinal: boolean }; + } = {}; + channel.bind( + "chunked-" + event, + (data: { id: string; index: number; chunk: string; final: boolean }) => { + if (!events.hasOwnProperty(data.id)) { + events[data.id] = { chunks: [], receivedFinal: false }; + } + const ev = events[data.id]; + ev.chunks[data.index] = data.chunk; + if (data.final) ev.receivedFinal = true; + if ( + ev.receivedFinal && + ev.chunks.length === Object.keys(ev.chunks).length + ) { + callback(JSON.parse(ev.chunks.join(""))); + delete events[data.id]; + } + } + ); + } - /** - * Subscribes to a trigger channel for a client and handles chunked data. - * @param {string} clientId - The unique identifier for the client subscribing to the events. - * @param {(data: any) => void} fn - The callback function to execute when trigger data is received. - */ - static triggerSubscribe(clientId: string, fn: (data: TriggerData) => void): void { - var channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`); - PusherUtils.bindWithChunking(channel, "trigger_to_client", fn); + /** + * Subscribes to a trigger channel for a client and handles chunked data. + * @param {string} clientId - The unique identifier for the client subscribing to the events. + * @param {(data: any) => void} fn - The callback function to execute when trigger data is received. + */ + static triggerSubscribe( + clientId: string, + fn: (data: TriggerData) => void + ): void { + const channel = PusherUtils.pusherClient.subscribe( + `private-${clientId}_triggers` + ); + PusherUtils.bindWithChunking(channel, "trigger_to_client", fn); - logger.info(`Subscribed to triggers. You should start receiving events now.`); - } + logger.info( + `Subscribed to triggers. You should start receiving events now.` + ); + } - static triggerUnsubscribe(clientId: string): void { - PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`); - } + static triggerUnsubscribe(clientId: string): void { + PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`); + } } diff --git a/js/src/sdk/utils/telemetry/events.ts b/js/src/sdk/utils/telemetry/events.ts index 9e3ae84fb4..c8f1a426c5 100644 --- a/js/src/sdk/utils/telemetry/events.ts +++ b/js/src/sdk/utils/telemetry/events.ts @@ -1,5 +1,5 @@ export enum TELEMETRY_EVENTS { - SDK_INITIALIZED = "SDK_INITIALIZED", - SDK_METHOD_INVOKED = "SDK_METHOD_INVOKED", - CLI_INVOKED = "CLI_INVOKED" -} \ No newline at end of file + SDK_INITIALIZED = "SDK_INITIALIZED", + SDK_METHOD_INVOKED = "SDK_METHOD_INVOKED", + CLI_INVOKED = "CLI_INVOKED", +} diff --git a/js/src/sdk/utils/telemetry/index.ts b/js/src/sdk/utils/telemetry/index.ts index e3625ca7cd..64ea610434 100644 --- a/js/src/sdk/utils/telemetry/index.ts +++ b/js/src/sdk/utils/telemetry/index.ts @@ -5,60 +5,68 @@ import { BatchProcessor } from "../base/batchProcessor"; import { getEnvVariable } from "../../../utils/shared"; export class TELEMETRY_LOGGER { - private static batchProcessor = new BatchProcessor(1000, 100, async (data) => { - await TELEMETRY_LOGGER.sendTelemetry(data as Record[]); - }); - - private static createTelemetryWrapper(method: Function, className: string) { - return async (...args: unknown[]) => { - const payload = { - eventName: method.name, - data: { className, args }, - sdk_meta: ComposioSDKContext - }; - - TELEMETRY_LOGGER.batchProcessor.pushItem(payload); - return method(...args); - }; + private static batchProcessor = new BatchProcessor( + 1000, + 100, + async (data) => { + await TELEMETRY_LOGGER.sendTelemetry(data as Record[]); } + ); - private static async sendTelemetry(payload: Record[]) { - const isTelementryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true"; - if(isTelementryDisabled) { - return; - } - const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`; - const reqPayload = { - data: { events: payload }, - url, - method: "POST", - headers: { "Content-Type": "application/json" } - }; + private static createTelemetryWrapper(method: Function, className: string) { + return async (...args: unknown[]) => { + const payload = { + eventName: method.name, + data: { className, args }, + sdk_meta: ComposioSDKContext, + }; - const isBrowser = typeof window !== "undefined"; - if (isBrowser) { - await sendBrowserReq(reqPayload); - } else { - await sendProcessReq(reqPayload); - } - } + TELEMETRY_LOGGER.batchProcessor.pushItem(payload); + return method(...args); + }; + } - static wrapClassMethodsForTelemetry(classInstance: any, methods: string[]) { - methods.forEach((method) => { - classInstance[method] = TELEMETRY_LOGGER.createTelemetryWrapper(classInstance[method], classInstance.constructor.name); - }); + private static async sendTelemetry(payload: Record[]) { + const isTelementryDisabled = + getEnvVariable("TELEMETRY_DISABLED", "false") === "true"; + if (isTelementryDisabled) { + return; } + const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`; + const reqPayload = { + data: { events: payload }, + url, + method: "POST", + headers: { "Content-Type": "application/json" }, + }; - static manualTelemetry(eventName: string, data: Record) { - const payload = { - eventName, - data, - sdk_meta: ComposioSDKContext - }; - TELEMETRY_LOGGER.batchProcessor.pushItem(payload); + const isBrowser = typeof window !== "undefined"; + if (isBrowser) { + await sendBrowserReq(reqPayload); + } else { + await sendProcessReq(reqPayload); } + } - static wrapFunctionForTelemetry(func: Function, className: string) { - return TELEMETRY_LOGGER.createTelemetryWrapper(func, className); - } + static wrapClassMethodsForTelemetry(classInstance: any, methods: string[]) { + methods.forEach((method) => { + classInstance[method] = TELEMETRY_LOGGER.createTelemetryWrapper( + classInstance[method], + classInstance.constructor.name + ); + }); + } + + static manualTelemetry(eventName: string, data: Record) { + const payload = { + eventName, + data, + sdk_meta: ComposioSDKContext, + }; + TELEMETRY_LOGGER.batchProcessor.pushItem(payload); + } + + static wrapFunctionForTelemetry(func: Function, className: string) { + return TELEMETRY_LOGGER.createTelemetryWrapper(func, className); + } } diff --git a/js/src/utils/external.ts b/js/src/utils/external.ts index 319010ac05..dd8e499c2a 100644 --- a/js/src/utils/external.ts +++ b/js/src/utils/external.ts @@ -1,27 +1,31 @@ - import { spawn } from "child_process"; import { IS_DEVELOPMENT_OR_CI, TELEMETRY_URL } from "../sdk/utils/constants"; import { serializeValue } from "../sdk/utils/common"; +import logger from "./logger"; /** * Sends a reporting payload to the telemetry server using a child process. * This function is intended for use in Node.js environments. - * + * * @param {any} reportingPayload - The payload to be sent to the telemetry server. */ -export async function sendProcessReq(info:{ - url: string, - method: string, - headers: Record, - data: Record +export async function sendProcessReq(info: { + url: string; + method: string; + headers: Record; + data: Record; }) { - if(IS_DEVELOPMENT_OR_CI){ - console.log(`Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`); - return true; - } - try { - // Spawn a child process to execute a Node.js script - const child = spawn('node', ['-e', ` + if (IS_DEVELOPMENT_OR_CI) { + console.log( + `Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}` + ); + return true; + } + try { + // Spawn a child process to execute a Node.js script + const child = spawn("node", [ + "-e", + ` const http = require('http'); const options = { hostname: '${info.url}', @@ -44,54 +48,57 @@ export async function sendProcessReq(info:{ req.write(JSON.stringify(info.data)); req.end(); - `]); - // Close the stdin stream - child.stdin.end(); - } catch (error) { - console.error("Error sending error to telemetry", error); - // DO NOTHING - } + `, + ]); + // Close the stdin stream + child.stdin.end(); + } catch (error) { + logger.error("Error sending error to telemetry", error); + // DO NOTHING + } } /** * Sends a reporting payload to the telemetry server using XMLHttpRequest. * This function is intended for use in browser environments. - * + * * @param {any} reportingPayload - The payload to be sent to the telemetry server. */ -export async function sendBrowserReq(info:{ - url: string, - method: string, - headers: Record, - data: Record +export async function sendBrowserReq(info: { + url: string; + method: string; + headers: Record; + data: Record; }) { - if(IS_DEVELOPMENT_OR_CI){ - console.log(`Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}`); - return true; - } - try { - // Create a new XMLHttpRequest object - const xhr = new XMLHttpRequest(); - // Open a new POST request to the telemetry server - xhr.open(info.method, info.url, true); - // Set the request header to indicate JSON content - xhr.setRequestHeader('Content-Type', 'application/json'); - Object.entries(info.headers || {}).forEach(([key, value]) => { - xhr.setRequestHeader(key, value); - }); + if (IS_DEVELOPMENT_OR_CI) { + logger.debug( + `Hitting ${info.url}[${info.method}] with ${serializeValue(info.data)}` + ); + return true; + } + try { + // Create a new XMLHttpRequest object + const xhr = new XMLHttpRequest(); + // Open a new POST request to the telemetry server + xhr.open(info.method, info.url, true); + // Set the request header to indicate JSON content + xhr.setRequestHeader("Content-Type", "application/json"); + Object.entries(info.headers || {}).forEach(([key, value]) => { + xhr.setRequestHeader(key, value); + }); // Define the onload event handler - xhr.onload = function() { - // Log the response if the request was successful - if (xhr.status === 200) { - console.log(xhr.response); - } + xhr.onload = function () { + // Log the response if the request was successful + if (xhr.status === 200) { + logger.debug(xhr.response); + } }; // Send the reporting payload as a JSON string - xhr.send(JSON.stringify(info.data)); - } catch (error) { - console.error("Error sending error to telemetry", error); - // DO NOTHING - } -} \ No newline at end of file + xhr.send(JSON.stringify(info.data)); + } catch (error) { + logger.error("Error sending error to telemetry", error); + // DO NOTHING + } +} diff --git a/js/src/utils/logger.ts b/js/src/utils/logger.ts index 1d53b9e7ea..1f644514ef 100644 --- a/js/src/utils/logger.ts +++ b/js/src/utils/logger.ts @@ -1,20 +1,20 @@ -import { getEnvVariable } from './shared'; -import winston from 'winston'; +import { getEnvVariable } from "./shared"; +import winston from "winston"; // Define log levels with corresponding priorities const LOG_LEVELS = { error: 0, // Highest priority - critical errors - warn: 1, // Warning messages - info: 2, // General information - debug: 3 // Debug information + warn: 1, // Warning messages + info: 2, // General information + debug: 3, // Debug information } as const; // Define colors for each log level for better visibility const LOG_COLORS = { - error: 'red', // Critical errors in red - warn: 'yellow', // Warnings in yellow - info: 'blue', // Info in blue - debug: 'green' // Debug in green + error: "red", // Critical errors in red + warn: "yellow", // Warnings in yellow + info: "blue", // Info in blue + debug: "green", // Debug in green }; /** @@ -23,8 +23,13 @@ const LOG_COLORS = { * @returns {keyof typeof LOG_LEVELS} The current log level */ export const getLogLevel = (): keyof typeof LOG_LEVELS => { - const envLevel = getEnvVariable("COMPOSIO_LOGGING_LEVEL", "info")?.toLowerCase(); - return (envLevel && envLevel in LOG_LEVELS) ? envLevel as keyof typeof LOG_LEVELS : 'info'; + const envLevel = getEnvVariable( + "COMPOSIO_LOGGING_LEVEL", + "info" + )?.toLowerCase(); + return envLevel && envLevel in LOG_LEVELS + ? (envLevel as keyof typeof LOG_LEVELS) + : "info"; }; // Configure winston colors @@ -36,15 +41,15 @@ const logFormat = winston.format.combine( winston.format.colorize(), winston.format.printf(({ timestamp, level, message, ...metadata }) => { // Format timestamp for readability - const formattedTime = timestamp.slice(5, 22).replace('T', ' '); - + const formattedTime = timestamp.slice(5, 22).replace("T", " "); + // Handle metadata serialization - let metadataStr = ''; + let metadataStr = ""; if (Object.keys(metadata).length) { try { metadataStr = ` - ${JSON.stringify(metadata)}`; } catch { - metadataStr = ' - [Circular metadata object]'; + metadataStr = " - [Circular metadata object]"; } } @@ -62,10 +67,10 @@ const logger = winston.createLogger({ transports: [ new winston.transports.Console({ handleExceptions: false, - handleRejections: false - }) + handleRejections: false, + }), ], - exitOnError: false // Prevent crashes on uncaught exceptions + exitOnError: false, // Prevent crashes on uncaught exceptions }); export default logger; diff --git a/js/src/utils/shared.spec.ts b/js/src/utils/shared.spec.ts index 8453153651..ecba936ca4 100644 --- a/js/src/utils/shared.spec.ts +++ b/js/src/utils/shared.spec.ts @@ -1,59 +1,71 @@ -import { jsonSchemaToTsType, jsonSchemaToModel, getEnvVariable, nodeExternalRequire } from './shared'; -import z from 'zod'; +import { + jsonSchemaToTsType, + jsonSchemaToModel, + getEnvVariable, + nodeExternalRequire, +} from "./shared"; +import z from "zod"; -describe('shared utilities', () => { - describe('jsonSchemaToTsType', () => { - it('should convert json schema types to TypeScript types', () => { - expect(jsonSchemaToTsType({ type: 'string' })).toBe(String); - expect(jsonSchemaToTsType({ type: 'integer' })).toBe(Number); - expect(jsonSchemaToTsType({ type: 'number' })).toBe(Number); - expect(jsonSchemaToTsType({ type: 'boolean' })).toBe(Boolean); - expect(jsonSchemaToTsType({ type: 'null' })).toBe(null); - expect(() => jsonSchemaToTsType({ type: 'unknown' })).toThrow('Unsupported JSON schema type: unknown'); +describe("shared utilities", () => { + describe("jsonSchemaToTsType", () => { + it("should convert json schema types to TypeScript types", () => { + expect(jsonSchemaToTsType({ type: "string" })).toBe(String); + expect(jsonSchemaToTsType({ type: "integer" })).toBe(Number); + expect(jsonSchemaToTsType({ type: "number" })).toBe(Number); + expect(jsonSchemaToTsType({ type: "boolean" })).toBe(Boolean); + expect(jsonSchemaToTsType({ type: "null" })).toBe(null); + expect(() => jsonSchemaToTsType({ type: "unknown" })).toThrow( + "Unsupported JSON schema type: unknown" + ); }); }); - describe('jsonSchemaToModel', () => { - it('should convert json schema to zod model', () => { + describe("jsonSchemaToModel", () => { + it("should convert json schema to zod model", () => { const schema = { - type: 'object', + type: "object", properties: { - name: { type: 'string' }, - age: { type: 'integer' }, + name: { type: "string" }, + age: { type: "integer" }, }, - required: ['name'] + required: ["name"], }; const model = jsonSchemaToModel(schema); expect(model).toBeInstanceOf(z.ZodObject); - expect(() => model.parse({ name: 'John', age: 'not a number' })).toThrow(); - expect(model.parse({ name: 'John', age: 30 })).toEqual({ name: 'John', age: 30 }); + expect(() => + model.parse({ name: "John", age: "not a number" }) + ).toThrow(); + expect(model.parse({ name: "John", age: 30 })).toEqual({ + name: "John", + age: 30, + }); }); }); - describe('getEnvVariable', () => { - it('should return the environment variable if set', () => { - process.env.TEST_VAR = 'test'; - expect(getEnvVariable('TEST_VAR')).toBe('test'); + describe("getEnvVariable", () => { + it("should return the environment variable if set", () => { + process.env.TEST_VAR = "test"; + expect(getEnvVariable("TEST_VAR")).toBe("test"); }); - it('should return undefined if the environment variable is not set', () => { + it("should return undefined if the environment variable is not set", () => { delete process.env.TEST_VAR; - expect(getEnvVariable('TEST_VAR')).toBeUndefined(); + expect(getEnvVariable("TEST_VAR")).toBeUndefined(); }); - it('should return the default value if the environment variable is not set and default is provided', () => { - expect(getEnvVariable('TEST_VAR', 'default')).toBe('default'); + it("should return the default value if the environment variable is not set and default is provided", () => { + expect(getEnvVariable("TEST_VAR", "default")).toBe("default"); }); }); - describe('nodeExternalRequire', () => { - it('should require a module', () => { - const module = nodeExternalRequire('path'); + describe("nodeExternalRequire", () => { + it("should require a module", () => { + const module = nodeExternalRequire("path"); expect(module).toBeDefined(); }); - it('should return null if the module cannot be required', () => { - const module = nodeExternalRequire('nonexistent-module'); + it("should return null if the module cannot be required", () => { + const module = nodeExternalRequire("nonexistent-module"); expect(module).toBeNull(); }); }); diff --git a/js/src/utils/shared.ts b/js/src/utils/shared.ts index 60933f4639..118549bff4 100644 --- a/js/src/utils/shared.ts +++ b/js/src/utils/shared.ts @@ -2,159 +2,212 @@ import z from "zod"; import logger from "./logger"; type SchemaTypeToTsType = { - [key: string]: any; + [key: string]: any; }; const PYDANTIC_TYPE_TO_TS_TYPE: SchemaTypeToTsType = { - "string": String, - "integer": Number, - "number": Number, - "boolean": Boolean, - "null": null + string: String, + integer: Number, + number: Number, + boolean: Boolean, + null: null, }; - export function jsonSchemaToTsType(jsonSchema: Record): any { - if (!jsonSchema.type) { - jsonSchema.type = "string"; - } - const type = jsonSchema.type as string; - - if (type === "array") { - const itemsSchema = jsonSchema.items; - if (itemsSchema) { - const ItemType = jsonSchemaToTsType(itemsSchema); - return ItemType; - } - return Array; + if (!jsonSchema.type) { + jsonSchema.type = "string"; + } + const type = jsonSchema.type as string; + + if (type === "array") { + const itemsSchema = jsonSchema.items; + if (itemsSchema) { + const ItemType = jsonSchemaToTsType(itemsSchema); + return ItemType; } + return Array; + } - if (type === "object") { - const properties = jsonSchema.properties; - if (properties) { - const nestedModel = jsonSchemaToModel(jsonSchema); - return nestedModel; - } - return Object; + if (type === "object") { + const properties = jsonSchema.properties; + if (properties) { + const nestedModel = jsonSchemaToModel(jsonSchema); + return nestedModel; } + return Object; + } - const tsType = PYDANTIC_TYPE_TO_TS_TYPE[type]; - if (tsType !== undefined) { - return tsType; - } + const tsType = PYDANTIC_TYPE_TO_TS_TYPE[type]; + if (tsType !== undefined) { + return tsType; + } - throw new Error(`Unsupported JSON schema type: ${type}`); + throw new Error(`Unsupported JSON schema type: ${type}`); } export function jsonSchemaToTsField( - name: string, - jsonSchema: Record, - required: string[] + name: string, + jsonSchema: Record, + required: string[] ): [any, any] { - const description = jsonSchema.description; - const examples = jsonSchema.examples || []; - return [ - jsonSchemaToTsType(jsonSchema), - { - description: description, - examples: examples, - required: required.includes(name), - default: required.includes(name) ? undefined : null, - }, - ]; + const description = jsonSchema.description; + const examples = jsonSchema.examples || []; + return [ + jsonSchemaToTsType(jsonSchema), + { + description: description, + examples: examples, + required: required.includes(name), + default: required.includes(name) ? undefined : null, + }, + ]; } - function jsonSchemaPropertiesToTSTypes(value: any): z.ZodTypeAny { - if(!value.type) { - return z.object({}); - } + if (!value.type) { + return z.object({}); + } + + let zodType; + switch (value.type) { + case "string": + zodType = z + .string() + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "number": + zodType = z + .number() + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "integer": + zodType = z + .number() + .int() + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "boolean": + zodType = z + .boolean() + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "array": + zodType = z + .array(jsonSchemaPropertiesToTSTypes(value.items)) + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "object": + zodType = jsonSchemaToModel(value).describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + break; + case "null": + zodType = z.null().describe(value.description || ""); + break; + default: + throw new Error(`Unsupported JSON schema type: ${value.type}`); + } + + return zodType; +} +export function jsonSchemaToModel( + jsonSchema: Record +): z.ZodObject { + const properties = jsonSchema.properties; + const requiredFields = jsonSchema.required || []; + if (!properties) { + return z.object({}); + } + + const zodSchema: Record = {}; + for (const [key, _] of Object.entries(properties)) { + const value = _ as any; let zodType; - switch (value.type) { - case "string": - zodType = z.string().describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "number": - zodType = z.number().describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "integer": - zodType = z.number().int().describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "boolean": - zodType = z.boolean().describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "array": - zodType = z.array(jsonSchemaPropertiesToTSTypes(value.items)).describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "object": - zodType = jsonSchemaToModel(value).describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - break; - case "null": - zodType = z.null().describe(value.description || "") - break; - default: - throw new Error(`Unsupported JSON schema type: ${value.type}`); + if (value.anyOf) { + const anyOfTypes = value.anyOf.map((schema: any) => + jsonSchemaPropertiesToTSTypes(schema) + ); + zodType = z + .union(anyOfTypes) + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + } else if (value.allOf) { + const allOfTypes = value.allOf.map((schema: any) => + jsonSchemaPropertiesToTSTypes(schema) + ); + zodType = z + .intersection( + allOfTypes[0], + allOfTypes + .slice(1) + .reduce( + (acc: z.ZodTypeAny, schema: z.ZodTypeAny) => acc.and(schema), + allOfTypes[0] + ) + ) + .describe( + (value.description || "") + + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "") + ); + } else { + if (!value.type) { + value.type = "string"; + } + zodType = jsonSchemaPropertiesToTSTypes(value); } - return zodType; -} - -export function jsonSchemaToModel(jsonSchema: Record): z.ZodObject { - const properties = jsonSchema.properties; - const requiredFields = jsonSchema.required || []; - if (!properties) { - return z.object({}); + if (value.description) { + zodType = zodType.describe(value.description); } - const zodSchema: Record = {}; - for (const [key, _] of Object.entries(properties)) { - const value = _ as any; - let zodType; - if (value.anyOf) { - const anyOfTypes = value.anyOf.map((schema: any) => jsonSchemaPropertiesToTSTypes(schema)); - zodType = z.union(anyOfTypes).describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - } else if (value.allOf) { - const allOfTypes = value.allOf.map((schema: any) => jsonSchemaPropertiesToTSTypes(schema)); - zodType = z.intersection(allOfTypes[0], allOfTypes.slice(1).reduce((acc: z.ZodTypeAny, schema: z.ZodTypeAny) => acc.and(schema), allOfTypes[0])).describe((value.description || "") + (value.examples ? `\nExamples: ${value.examples.join(", ")}` : "")); - } else { - if(!value.type) { - value.type = "string" - } - zodType = jsonSchemaPropertiesToTSTypes(value); - } - - if (value.description) { - zodType = zodType.describe(value.description); - } - - if (requiredFields.includes(key)) { - zodSchema[key] = zodType; - } else { - zodSchema[key] = zodType.optional(); - } + if (requiredFields.includes(key)) { + zodSchema[key] = zodType; + } else { + zodSchema[key] = zodType.optional(); } + } - return z.object(zodSchema); -} - -export const getEnvVariable = (name: string, defaultValue: string | undefined = undefined): string | undefined => { - try { - return process.env[name] || defaultValue; - } catch (e) { - return defaultValue; - } + return z.object(zodSchema); } +export const getEnvVariable = ( + name: string, + defaultValue: string | undefined = undefined +): string | undefined => { + try { + return process.env[name] || defaultValue; + } catch (_e) { + return defaultValue; + } +}; export const nodeExternalRequire = (name: string) => { - try { - if (typeof process !== 'undefined') { - return require(name); - } else { - return require(`external:${name}`); - } - } catch(err) { - return null + try { + if (typeof process !== "undefined") { + return require(name); + } else { + return require(`external:${name}`); } -} \ No newline at end of file + } catch (err) { + return null; + } +}; diff --git a/js/tests/test_examples.test.ts b/js/tests/test_examples.test.ts new file mode 100644 index 0000000000..7952aa7396 --- /dev/null +++ b/js/tests/test_examples.test.ts @@ -0,0 +1,59 @@ +/** + * E2E Tests for plugin demos and examples. + */ + +const { execFile } = require("child_process"); +const path = require("path"); +const { promisify } = require("util"); +const execFileAsync = promisify(execFile); + +// Paths +const EXAMPLES_PATH = path.resolve(__dirname, "../examples"); + +// Plugin test definitions +const EXAMPLES = { + portfolio_generator: { + file: path.join(EXAMPLES_PATH, "portfolio-generator", "demo.mjs"), + match: { + type: "stdout", + values: ["🎉Output from agent: "], + }, + }, + lead_generator_agent: { + file: path.join(EXAMPLES_PATH, "reddit-research", "demo.mjs"), + match: { + type: "stdout", + values: ["🎉Output from agent: "], + }, + }, + lead_outreach_agent: { + file: path.join(EXAMPLES_PATH, "lead_outreach_agent", "demo.mjs"), + match: { + type: "stdout", + values: ["🎉Output from agent: "], + }, + }, +}; + +describe("E2E Tests for plugin demos and examples", () => { + jest.setTimeout(300000); // Set timeout to 5 minutes + + for (const [exampleName, example] of Object.entries(EXAMPLES)) { + test(`should run ${exampleName} example successfully`, async () => { + const options = { + env: { ...process.env }, + cwd: example.cwd || process.cwd(), + }; + + const { stdout, stderr } = await execFileAsync( + "node", + [example.file], + options, + ); + const output = example.match.type === "stdout" ? stdout : stderr; + for (const match of example.match.values) { + expect(output).toContain(match); + } + }); + } +});