Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
merge cli (#1649)
Rahul Tarak1d02d3e49591
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 000000000..e5d0f14e0--- /dev/null+++ b/.dockerignore@@ -0,0 +1,28 @@+# Git+.git+.gitignore++# Docker+Dockerfile+.dockerignore++# Node.js+node_modules+/packages/*/node_modules+/packages/*/dist+/dist+npm-debug.log*+yarn-debug.log*+yarn-error.log*++# Editor directories and files+.idea+.vscode+*.suo+*.ntvs*+*.njsproj+*.sln++# OS generated files+.DS_Store+Thumbs.dbdiff --git a/Dockerfile b/Dockerfilenew file mode 100644index 000000000..542b35c8c--- /dev/null+++ b/Dockerfile@@ -0,0 +1,45 @@+# Stage 1: Build the CLI binary+FROM debian:bookworm-slim AS builder++# Install dependencies+RUN apt-get update && apt-get install -y \+ git \+ curl \+ unzip \+ && rm -rf /var/lib/apt/lists/*++# Install Node.js, pnpm and bun+RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \+ && apt-get install -y nodejs \+ && npm install -g [email protected] \+ && curl -fsSL https://bun.sh/install | bash++# Add bun to PATH+ENV PATH="/root/.bun/bin:${PATH}"++# Clone the repository+WORKDIR /app+COPY . .++# Build the monorepo+RUN pnpm install+RUN pnpm build++# Build the CLI binary+WORKDIR /app/packages/cli+RUN pnpm build:bin++# Stage 2: Create a minimal runtime image+FROM debian:bookworm-slim++# Copy the CLI binary from the builder stage+COPY --from=builder /app/packages/cli/dist/composio /composio++# Make the binary executable+RUN chmod +x /composio++# Create directory for user data+WORKDIR /root/.composio++# Set the entrypoint+ENTRYPOINT ["/composio", "--version"]diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 09a97909b..5dc3257b4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -119,7 +119,7 @@ importers:version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])yaml:specifier: ^2.8.0version: 2.8.0@@ -282,7 +282,7 @@ importers:version: link:../../packages/providers/mastra'@mastra/core':specifier: ^0.10.0dotenv:specifier: ^16.4.1version: 16.5.0@@ -448,6 +448,76 @@ importers:specifier: ^5.8.3version: 5.8.3+ ts/packages/cli:+ dependencies:+ '@composio/client':+ specifier: 0.1.0-alpha.17+ version: 0.1.0-alpha.17+ '@composio/core':+ specifier: workspace:*+ version: link:../core+ '@composio/ts-builders':+ specifier: workspace:*+ version: link:../ts-builders+ '@effect/cli':+ specifier: ^0.63.11+ version: 0.63.11(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@effect/platform-bun':+ specifier: ^0.69.16+ version: 0.69.16(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@effect/platform-node-shared':+ specifier: ^0.40.2+ version: 0.40.2(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ chalk:+ specifier: ^5.4.1+ version: 5.4.1+ effect:+ specifier: ^3.16.8+ version: 3.16.8+ effect-errors:+ specifier: ^1.10.11+ version: 1.10.11(ff5edfb43a1891ed491370151a2c33b9)+ indent-string:+ specifier: ^5.0.0+ version: 5.0.0+ semver:+ specifier: ^7.7.2+ version: 7.7.2+ superjson:+ specifier: ^2.2.2+ version: 2.2.2+ devDependencies:+ '@effect/eslint-plugin':+ specifier: ^0.3.2+ version: 0.3.2+ '@effect/platform':+ specifier: ^0.84.11+ version: 0.84.11([email protected])+ '@effect/vitest':+ specifier: ^0.23.8+ version: 0.23.8([email protected])([email protected](@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected]))+ '@types/bun':+ specifier: ^1.2.16+ version: 1.2.16+ '@types/semver':+ specifier: ^7.7.0+ version: 7.7.0+ tempy:+ specifier: ^3.1.0+ version: 3.1.0+ tsup:+ specifier: ^8.5.0+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ tsx:+ specifier: ^4.20.3+ version: 4.20.3+ typescript:+ specifier: ^5.8.3+ version: 5.8.3+ vitest:+ specifier: ^3.2.4+ version: 3.2.4(@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected])+ts/packages/core:dependencies:'@composio/client':@@ -508,13 +578,13 @@ importers:version: 24.0.3tsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/anthropic:dependencies:@@ -527,13 +597,13 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/cloudflare:dependencies:@@ -546,13 +616,13 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/google:dependencies:@@ -565,7 +635,7 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3@@ -581,32 +651,32 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/mastra:dependencies:'@mastra/core':specifier: ^0.10.0devDependencies:'@composio/core':specifier: workspace:*version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/openai:dependencies:@@ -619,13 +689,13 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/openai-agents:dependencies:@@ -638,13 +708,13 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])ts/packages/providers/vercel:dependencies:@@ -657,13 +727,32 @@ importers:version: link:../../coretsup:specifier: ^8.4.0- version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])typescript:specifier: ^5.8.3version: 5.8.3vitest:specifier: ^3.1.4- version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ version: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])++ ts/packages/ts-builders:+ dependencies:+ '@babel/helper-validator-identifier':+ specifier: ^7.27.1+ version: 7.27.1+ devDependencies:+ '@types/babel__helper-validator-identifier':+ specifier: ^7.15.2+ version: 7.15.2+ helper-validator-identifier:+ specifier: link:@types/@babel/helper-validator-identifier+ version: link:@types/@babel/helper-validator-identifier+ tsup:+ specifier: ^8.4.0+ version: 8.5.0([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: ^3.1.4+ version: 3.2.4(@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected])packages:@@ -851,6 +940,10 @@ packages:resolution: {integrity: sha512-DIIotRnefVL6DiaHtO6/21DhJ4JZnnIwdNbpwiAhdt/AVbttcE4yw925gsjur0OGv5BTYXQXU3YnANBYnZjuQA==}engines: {node: '>=18.0.0'}+ '@babel/[email protected]':+ resolution: {integrity: sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow==}+ engines: {node: '>=6.9.0'}+'@babel/[email protected]':resolution: {integrity: sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q==}engines: {node: '>=6.9.0'}@@ -922,6 +1015,9 @@ packages:'@anthropic-ai/sdk': ^0.52.0'@composio/core': 0.1.22+ '@composio/[email protected]':+ resolution: {integrity: sha512-iNCDSgdwfFVsjbbyZIMknMPy4uO8Xw5+MP2aI+yoQo34VXF17Fi6ZHYirrJPf8RbdoRROZTDJjC/rU18mMzC2Q==}+'@composio/[email protected]':resolution: {integrity: sha512-b9KCO5gy0EsCG+nXikOdm17PiZZ85rw3vwu9aNRIse9rEj2FA1SScpP+P9GN4G0lQHl+QPyDuVvGa6U9AATFeg==}@@ -944,6 +1040,129 @@ packages:'@composio/core': 0.1.22ai: ^4.3.8+ '@dprint/[email protected]':+ resolution: {integrity: sha512-IB/GXdlMOvi0UhQQ9mcY15Fxcrc2JPadmo6tqefCNV0bptFq7YBpggzpqYXldBXDa04CbKJ+rDwO2eNRPE2+/g==}++ '@dprint/[email protected]':+ resolution: {integrity: sha512-tuKn4leCPItox1O4uunHcQF0QllDCvPWklnNQIh2PiWWVtRAGltJJnM4Cwj5AciplosD1Hiz7vAY3ew3crLb3A==}++ '@effect/[email protected]':+ resolution: {integrity: sha512-e95XKrCLHFKQor1hRWD5a1nh34cMNWfhaZrRc5iqI2sWUTQumV8rUUDAPMNHFzPC0tIrdO42wrOUhIgJs7i2iA==}+ peerDependencies:+ '@effect/platform': ^0.84.11+ '@effect/printer': ^0.44.7+ '@effect/printer-ansi': ^0.44.7+ effect: ^3.16.7++ '@effect/[email protected]':+ resolution: {integrity: sha512-oU/UDcKzQDPoEHW+1wMLxJRmdlA5n/Ek7AG0vrKFQ7AiBxUpJwlJlym8BVgpRBVs3VTI+Jwigmx5z8rp1dJA+g==}+ peerDependencies:+ '@effect/platform': ^0.85.1+ '@effect/rpc': ^0.62.2+ '@effect/sql': ^0.38.1+ '@effect/workflow': ^0.2.2+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-c4Vs9t3r54A4Zpl+wo8+PGzZz3JWYsip41H+UrebRLjQ2Hk/ap63IeCgN/HWcYtxtyhRopjp7gW9nOQ2Snbl+g==}++ '@effect/[email protected]':+ resolution: {integrity: sha512-puU0tZR+vEQ8RwdBXkMXVGlV5WG4tyVQA6J5LCJJoDnHDzNmEKsEjcjrD6YKmt/MNr9Jdm0H5LkkEfRYTiCL2g==}+ peerDependencies:+ '@effect/platform': ^0.85.1+ effect: ^3.16.8+ ioredis: ^5+ lmdb: ^3+ peerDependenciesMeta:+ ioredis:+ optional: true+ lmdb:+ optional: true++ '@effect/[email protected]':+ resolution: {integrity: sha512-5Mocp+ZfCZ4xw1kI5OmoTAzLKtHht8NisEwD66rc8wium+2elFxFsuiM2kGM3TYz9jC3vwkEXf1SXgecBLWz4A==}+ peerDependencies:+ '@effect/cluster': ^0.38.16+ '@effect/platform': ^0.84.11+ '@effect/rpc': ^0.61.15+ '@effect/sql': ^0.37.12+ effect: ^3.16.7++ '@effect/[email protected]':+ resolution: {integrity: sha512-aJ7jVm9V+SEeNumRmHb+TxD0C38uv/1LLfBHB2Qg+xb5UjnZhak8SzwolAgSKkMNDFpAAdF2AlxZ1tO/HfhCiw==}+ peerDependencies:+ '@effect/cluster': ^0.38.16+ '@effect/platform': ^0.84.11+ '@effect/rpc': ^0.61.15+ '@effect/sql': ^0.37.12+ effect: ^3.16.7++ '@effect/[email protected]':+ resolution: {integrity: sha512-f9FbZN1pTMlR4bTwlR/mER9Qqd1MwMdryn3cz5/lapmXvgrRxQ+vgGS15d286mZeoc6aHtXGEr0GgoPNDFscKw==}+ peerDependencies:+ '@effect/cluster': ^0.39.2+ '@effect/platform': ^0.85.1+ '@effect/rpc': ^0.62.2+ '@effect/sql': ^0.38.1+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-EkmmRnH9m2ya+a4Yf7OTXNCkF1YO6w8yIfd6DwNfbFCsCBDHHcat5HgJpjPvsAWtbV9ZBaF0vfFXbbKfJx5Jfg==}+ peerDependencies:+ '@effect/cluster': ^0.39.2+ '@effect/platform': ^0.85.1+ '@effect/rpc': ^0.62.2+ '@effect/sql': ^0.38.1+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-u3eURhaF38e8jqq/JC2NW9EDHUFVDETD/JLEFtFi7N6RnAUF90qaC8sRcoK5xe8UAo3/fJDQ+sEfDqYonUa30w==}+ peerDependencies:+ effect: ^3.16.7++ '@effect/[email protected]':+ resolution: {integrity: sha512-HFatTgDyPgXc0Kbw2BH0nUht0ViAPukggIHuxGDm1EN0G7uKX9qXHLkFaQ7HGhotNOuf2hC6AXaKkzWOhxWp1A==}+ peerDependencies:+ '@effect/typeclass': ^0.35.8+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-dWJCAi/04W5VIfo0C9u9M6gPwH2Ki+NHDqcUi0qfghoGyG9wmA6bhoq7RAvzrVSL+59tuhsKTV9y4A5dYCVyLw==}+ peerDependencies:+ '@effect/typeclass': ^0.35.8+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-m9Vit6U0hZ/Yt/yKdz5fBoHI7cY4qFJdidYZTVqzAo5tctKQtfJFKjAn4Oq0TWVfbTC7JrCK0GM51j5iQuI33Q==}+ peerDependencies:+ '@effect/platform': ^0.85.1+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-oS5s8j8C1W7rugZeDpwfRjrjfRaqUqhO+wtL1yRgXqE0px7fVI3y2Am5f6aq63cR9UMKOwFc5NzEl3Af9uYlSw==}+ peerDependencies:+ '@effect/experimental': ^0.49.1+ '@effect/platform': ^0.85.1+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-hDrILuHlFEtiPSADMX9YKicAa7tSDMqJPEMfBdUoE27cUHLg7qnr5EykLQzvBKPhlHAs9DHb5w/fp9WMV6WUpQ==}+ peerDependencies:+ effect: ^3.16.8++ '@effect/[email protected]':+ resolution: {integrity: sha512-yaAfl+qHb0jK38rl3HSd4cjmo4xcQQDKW/bCAhhi9zDlbIDzH+gsOHz094KoQ/kAlp0wOTgjquSI21FV4w9YXg==}+ peerDependencies:+ effect: ^3.16.8+ vitest: ^3.0.0++ '@effect/[email protected]':+ resolution: {integrity: sha512-fAXH0S3roA1LUFItlXmHZPaL57ZWxySf4QveidOoZuB+1rXVKk79OX++Y1G+l7Omugb7JzsyL1JCt5qo+Detzg==}+ peerDependencies:+ '@effect/platform': ^0.85.1+ '@effect/rpc': ^0.62.2+ effect: ^3.16.8+'@emnapi/[email protected]':resolution: {integrity: sha512-pBPWdu6MLKROBX05wSNKcNb++m5Er+KQ9QkB+WVM+pW2Kx9hoSrVTnu3BdkI5eBLZoKu/J6mW/B6i6bJB2ytXQ==}@@ -1455,6 +1674,36 @@ packages:resolution: {integrity: sha512-KG1CZhZfWg+u8pxeM/mByJDScJSrjjxLc8fwQqbsS8xCjBmQfMNEBTotYdNanKekepnfRI85GtgQlctLFpcYPw==}engines: {node: '>=18'}+ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==}+ cpu: [arm64]+ os: [darwin]++ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==}+ cpu: [x64]+ os: [darwin]++ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==}+ cpu: [arm64]+ os: [linux]++ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==}+ cpu: [arm]+ os: [linux]++ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==}+ cpu: [x64]+ os: [linux]++ '@msgpackr-extract/[email protected]':+ resolution: {integrity: sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==}+ cpu: [x64]+ os: [win32]+'@next/[email protected]':resolution: {integrity: sha512-OdiMrzCl2Xi0VTjiQQUK0Xh7bJHnOuET2s+3V+Y40WJBAXrJeGA3f+I8MZJ/YQ3mVGi5XGR1L66oFlgqXhQ4Vw==}@@ -1996,6 +2245,88 @@ packages:peerDependencies:'@opentelemetry/api': ^1.1.0+ '@parcel/[email protected]':+ resolution: {integrity: sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm64]+ os: [android]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm64]+ os: [darwin]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg==}+ engines: {node: '>= 10.0.0'}+ cpu: [x64]+ os: [darwin]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ==}+ engines: {node: '>= 10.0.0'}+ cpu: [x64]+ os: [freebsd]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm64]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm64]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A==}+ engines: {node: '>= 10.0.0'}+ cpu: [x64]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg==}+ engines: {node: '>= 10.0.0'}+ cpu: [x64]+ os: [linux]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==}+ engines: {node: '>= 10.0.0'}+ cpu: [arm64]+ os: [win32]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ==}+ engines: {node: '>= 10.0.0'}+ cpu: [ia32]+ os: [win32]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA==}+ engines: {node: '>= 10.0.0'}+ cpu: [x64]+ os: [win32]++ '@parcel/[email protected]':+ resolution: {integrity: sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==}+ engines: {node: '>= 10.0.0'}+'@pkgjs/[email protected]':resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}engines: {node: '>=14'}@@ -2367,6 +2698,9 @@ packages:resolution: {integrity: sha512-4QvC49HTteI1gfemu0I1syWovJgPvGn7CVUoN9ZFkdvr/cCFkrEL7qNCdx/2eICqDWEGnnr68oMdSIPCLAriSQ==}engines: {node: '>=18.0.0'}+ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}+'@swc/[email protected]':resolution: {integrity: sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==}@@ -2376,6 +2710,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-nD0Z9fNIZcxYX5Mai2CTmFD7wX7UldCkW2ezCF8D1T5hdiLsnTWDGRpfRYntU6VjTdLQjOvyszru7I1c1oCQew==}+ '@types/[email protected]':+ resolution: {integrity: sha512-l3dkwCt890NFhMwPKXbxsWXC0Por0/+KaFIiQP1j38/vWSH2P3Tn6m+IuJHkx2SBI3VLFqincFe9JtBk2NFHOw==}+'@types/[email protected]':resolution: {integrity: sha512-1aCZJ/6nSiViw339RsaNhkNoEloLaPzZhxMOYEa7OzRzO41IGg5n/7I43/ZIAW/c+Q6cT12Vf7fOZOoVIzb5BQ==}@@ -2550,6 +2887,9 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-W2RH2TPWVHA1o7UmaFKISPvdicFJH+mjykctJFoAkUw+SPTJTGjUNdKscFBrqM7IPnCVu6zihtKYa7TkZS1dkQ==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==}+'@vitest/[email protected]':resolution: {integrity: sha512-cP6fIun+Zx8he4rbWvi+Oya6goKQDZK+Yq4hhlggwQBbrlOQ4qtZ+G4nxB6ZnzI9lyIb+JnvyiJnPC2AGbKSPA==}peerDependencies:@@ -2561,18 +2901,41 @@ packages:vite:optional: true+ '@vitest/[email protected]':+ resolution: {integrity: sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true+'@vitest/[email protected]':resolution: {integrity: sha512-yFglXGkr9hW/yEXngO+IKMhP0jxyFw2/qys/CK4fFUZnSltD+MU7dVYGrH8rvPcK/O6feXQA+EU33gjaBBbAng==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==}+'@vitest/[email protected]':resolution: {integrity: sha512-83HWYisT3IpMaU9LN+VN+/nLHVBCSIUKJzGxC5RWUOsK1h3USg7ojL+UXQR3b4o4UBIWCYdD2fxuzM7PQQ1u8w==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==}+'@vitest/[email protected]':resolution: {integrity: sha512-9gIVWx2+tysDqUmmM1L0hwadyumqssOL1r8KJipwLx5JVYyxvVRfxvMq7DaWbZZsCqZnu/dZedaZQh4iYTtneA==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==}+'@vitest/[email protected]':resolution: {integrity: sha512-JHu9Wl+7bf6FEejTCREy+DmgWe+rQKbK+y32C/k5f4TBIAlijhJbRBIRIOCEpVevgRsCQR2iHRUH2/qKVM/plw==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==}+'@vitest/[email protected]':resolution: {integrity: sha512-9aR2tY/WT7GRHGEH/9sSIipJqeA21Eh3C6xmiOVmfyBCFmezUSUFLalpaSmRHlRzWCKQU10yz3AHhKuYcdnZGQ==}peerDependencies:@@ -2581,6 +2944,9 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-4zFBCU5Pf+4Z6v+rwnZ1HU1yzOKKvDkMXZrymE2PBlbjKJRlrOxbvpfPSvJTGRIwGoahaOGvp+kbCoxifhzJ1Q==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==}+resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}engines: {node: '>=6.5'}@@ -2680,6 +3046,9 @@ packages:resolution: {integrity: sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==}+ resolution: {integrity: sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==}+resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==}engines: {node: '>=8'}@@ -2883,6 +3252,10 @@ packages:resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}engines: {node: '>= 6'}+ resolution: {integrity: sha512-bKw/r35jR3HGt5PEPm1ljsQQGyCrR8sFGNiN5L+ykDHdpO8Smxkrkla9Yi6NkQyUrb8V54PGhfMs6NrIwtxtdw==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-7BeSFlfRzr1cbIfGYJW4jQ3BHwaObOaFKiRJIFuWOmvOrTABl1hbxGkWPA3C+uFw9CFXbZhrLWNyD7lhYy2Scg==}hasBin: true@@ -2939,6 +3312,13 @@ packages:resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w==}+ engines: {node: '>=12.13'}++ resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}+resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==}engines: {node: '>= 0.10'}@@ -2947,6 +3327,10 @@ packages:resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}engines: {node: '>= 8'}+ resolution: {integrity: sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}engines: {node: '>=4'}@@ -3013,6 +3397,11 @@ packages:resolution: {integrity: sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==}engines: {node: '>=8'}+ resolution: {integrity: sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==}+ engines: {node: '>=0.10'}+ hasBin: true+resolution: {integrity: sha512-3UDv+G9CsCKO1WKMGw9fwq/SWJYbI0c5Y7LU1AXYoDdbhE2AHQ6N6Nb34sG8Fj7T5APy8qXDCKuuIHd1BR0tVA==}engines: {node: '>=8'}@@ -3047,6 +3436,20 @@ packages:resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}+ resolution: {integrity: sha512-lTktjnqeHfXSGQuhHm4jGWdZFfiWVZQP+szeEOuEmGEa2n4tNAu0FGO3LgS6Vp9nOatINYE3u65dFf28TtxxkQ==}+ engines: {node: '>=20.x'}+ peerDependencies:+ '@effect/cluster': 0.x+ '@effect/platform': 0.x+ '@effect/platform-node': 0.x+ '@effect/rpc': 0.x+ '@effect/sql': 0.x+ effect: 3.x++ resolution: {integrity: sha512-E4U0MZFBun99myxOogy9ZZ1c3IYR47L/A5GqCP9Lp+6ORag0YLmGHOrYxQ3agN1FOMTrElgtJmciicwnHdE+Ug==}+resolution: {integrity: sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==}@@ -3230,12 +3633,19 @@ packages:resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==}engines: {node: '>=4'}+ resolution: {integrity: sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A==}+ engines: {node: '>=8.0.0'}+resolution: {integrity: sha512-dl0O9Vhju8IrcLndv2eU4ldt1ftXMqqfgN4H1cpmGV7P6jeB9FwpN9a2c8DPGE1Ys88rNUJVYDHq73CGAGOPfQ==}resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}+ resolution: {integrity: sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw==}+resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}engines: {node: '>=8.6.0'}@@ -3291,6 +3701,9 @@ packages:resolution: {integrity: sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-4GOTMrpGQVzsCH2ruUn2vmwzV/02zF4q+ybhCIrw/Rkt3L8KWcycdC6aJMctJzwN4fXD4SD5F/4B9Sksh5rE0A==}+resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}engines: {node: '>=8'}@@ -3457,6 +3870,10 @@ packages:resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-Pq0h+hvsVm6dDEa8x82GnLSYHOzNDt7f0ddFa3FqcQlgzEiptPqL+XrOJNavjOzSYiYWIrgeVYYgGlLmnxwilQ==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}engines: {node: '>= 0.4'}@@ -3575,9 +3992,17 @@ packages:resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}engines: {node: '>=0.8.19'}+ resolution: {integrity: sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}+ resolution: {integrity: sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==}+ engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}+resolution: {integrity: sha512-tyao/4Vo36XnUItZ7DnUXX4f1jVao2mSrleV/5IPtW/XAEA26hRVsbc68nuTEKWcr5vMP/1mVoT2O7u8H4v1Vg==}engines: {node: '>=18'}@@ -3645,6 +4070,10 @@ packages:resolution: {integrity: sha512-2AT6j+gXe/1ueqbW6fLZJiIw3F8iXGJtt0yDrZaBhAZEG1raiTxKWU+IPqMCzQAXOUCKdA4UDMgacKH25XG2Cw==}engines: {node: '>=4'}+ resolution: {integrity: sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==}+ engines: {node: '>=12.13'}+resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==}engines: {node: '>=0.10.0'}@@ -3865,6 +4294,9 @@ packages:resolution: {integrity: sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==}+ resolution: {integrity: sha512-wJzkKwJrheKtknCOKNEtDK4iqg/MxmZheEMtSTYvnzRdEYaZzmgH976nenp8WdJRdx5Vc1X/9MO0Oszl6ezeXg==}+resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}@@ -3936,6 +4368,11 @@ packages:engines: {node: '>=4'}hasBin: true+ resolution: {integrity: sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==}+ engines: {node: '>=10.0.0'}+ hasBin: true+resolution: {integrity: sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==}engines: {node: '>=12'}@@ -3978,6 +4415,16 @@ packages:resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}+ resolution: {integrity: sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==}+ hasBin: true++ resolution: {integrity: sha512-uaff7RG9VIC4jacFW9xzL3jc0iM32DNHe4jYVycBcjUePT/Klnfj7pqtWJt9khvDFizmjN2TlYniYmSS2LIaZg==}++ resolution: {integrity: sha512-c8eMDb1WwZcE02WVjHoOmUVk7fnKU/RmUcosHACglrWAuPQsEJv+E8430sXj6jNc1jHw0zrS16aCjQh4BcEb4A==}+resolution: {integrity: sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==}hasBin: true@@ -4026,6 +4473,9 @@ packages:sass:optional: true+ resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}+resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}engines: {node: '>=10.5.0'}@@ -4040,6 +4490,10 @@ packages:encoding:optional: true+ resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==}+ hasBin: true+resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==}engines: {node: '>=0.10.0'}@@ -4371,6 +4825,10 @@ packages:resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}engines: {node: '>= 0.8.0'}+ resolution: {integrity: sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==}+ engines: {node: '>=6.0.0'}+resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==}engines: {node: '>=10.13.0'}@@ -4410,6 +4868,9 @@ packages:resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}engines: {node: '>=6'}+ resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}+resolution: {integrity: sha512-wp3HqIIUc1GRyu1XrP6m2dgyE9MoCsXVsWNlohj0rjSkLf+a0jLvEyVubdg58oMk7bhjBWnFClgp8jfAa6Ak4Q==}@@ -4485,6 +4946,10 @@ packages:resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==}engines: {node: '>= 12.13.0'}+ resolution: {integrity: sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==}+ engines: {node: '>=0.10'}+resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}engines: {node: '>=0.10.0'}@@ -4764,6 +5229,10 @@ packages:resolution: {integrity: sha512-MJd5FeT32XBMElZuzOT7mMM9dZlBHMTVHadPV3QC/pNKfuCyMj1a9Ub30GH+LbsT8ows+cT/P/K7ks9yp6z3KA==}hasBin: true+ resolution: {integrity: sha512-5JRxVqC8I8NuOUjzBbvVJAKNM8qoVuH0O77h4WInc/qC2q5IreqKxYwgkga3PfA22OayK2ikceb/B26dztPl+Q==}+ engines: {node: '>=16'}+resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}engines: {node: '>=8'}@@ -4782,6 +5251,14 @@ packages:engines: {node: '>=14.0.0'}hasBin: true+ resolution: {integrity: sha512-nHc6S/bwIilKHNRgK/3jlhDoIHcp45YgyiwcAk46Tr0LfEqGBVpmiAyuiuxeVE44m3mXnEeVhaipLOEWmH+Njw==}+ engines: {node: '>=14.16'}++ resolution: {integrity: sha512-7jDLIdD2Zp0bDe5r3D2qtkd1QOCacylBuL7oa4udvN6v2pqr4+LcCr67C8DR1zkpaZ8XosF5m1yQSabKAW6f2g==}+ engines: {node: '>=14.16'}+resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==}engines: {node: '>=8'}@@ -4814,6 +5291,10 @@ packages:resolution: {integrity: sha512-7CotroY9a8DKsKprEy/a14aCCm8jYVmR7aFy4fpkZM8sdpNJbKkixuNjgM50yCmip2ezc8z4N7k3oe2+rfRJCQ==}engines: {node: ^18.0.0 || >=20.0.0}+ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}+ engines: {node: ^18.0.0 || >=20.0.0}+resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}engines: {node: '>=14.0.0'}@@ -4834,6 +5315,9 @@ packages:resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}engines: {node: '>=0.6'}+ resolution: {integrity: sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==}+resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}engines: {node: '>=6'}@@ -4887,6 +5371,11 @@ packages:engines: {node: '>=18.0.0'}hasBin: true+ resolution: {integrity: sha512-qjbnuR9Tr+FJOMBqJCW5ehvIo/buZq7vH7qD7JziU98h6l3qGy0a/yPFjwO+y0/T7GFpNgNAvEcPPVfyT8rrPQ==}+ engines: {node: '>=18.0.0'}+ hasBin: true+resolution: {integrity: sha512-ah6YnH2dErojhFooxEzmvsoZQTMImaruZhFPfMKPBq8sb+hALRdvBNLqfc8NWlZq576FkfRZ/MSi4SHvVFT9PQ==}cpu: [x64]@@ -4932,6 +5421,14 @@ packages:resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}engines: {node: '>=10'}+ resolution: {integrity: sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==}+ engines: {node: '>=12.20'}+resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}engines: {node: '>= 0.6'}@@ -4985,6 +5482,14 @@ packages:resolution: {integrity: sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==}+ resolution: {integrity: sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==}+ engines: {node: '>=20.18.1'}++ resolution: {integrity: sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}engines: {node: '>= 4.0.0'}@@ -5032,6 +5537,11 @@ packages:engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}hasBin: true+ resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true+resolution: {integrity: sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==}engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}@@ -5100,6 +5610,34 @@ packages:jsdom:optional: true+ resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@types/debug': ^4.1.12+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0+ '@vitest/browser': 3.2.4+ '@vitest/ui': 3.2.4+ happy-dom: '*'+ jsdom: '*'+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@types/debug':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true+resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}engines: {node: '>= 14'}@@ -5718,6 +6256,8 @@ snapshots:'@smithy/types': 4.3.1tslib: 2.8.1+ '@babel/[email protected]': {}+'@babel/[email protected]': {}'@cfworker/[email protected]': {}@@ -5871,6 +6411,8 @@ snapshots:'@anthropic-ai/sdk': 0.52.0'@composio/core': 0.1.22([email protected])+ '@composio/[email protected]': {}+'@composio/[email protected]': {}'@composio/[email protected]': {}@@ -5902,16 +6444,152 @@ snapshots:'@composio/core': 0.1.22([email protected])ai: 4.3.16([email protected])([email protected])- '@emnapi/[email protected]':- dependencies:- tslib: 2.8.1- optional: true+ '@dprint/[email protected]': {}- '@esbuild/[email protected]':- optional: true+ '@dprint/[email protected]': {}- '@esbuild/[email protected]':- optional: true+ '@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/platform': 0.84.11([email protected])+ effect: 3.16.8+ ini: 4.1.3+ toml: 3.0.0+ yaml: 2.8.0++ '@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/platform': 0.84.11([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ '@effect/workflow': 0.2.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected])+ effect: 3.16.8++ '@effect/[email protected]':+ dependencies:+ '@dprint/formatter': 0.4.1+ '@dprint/typescript': 0.91.8+ prettier-linter-helpers: 1.0.0++ dependencies:+ '@effect/platform': 0.84.11([email protected])+ effect: 3.16.8+ uuid: 11.1.0++ '@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/cluster': 0.39.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])+ '@effect/platform': 0.84.11([email protected])+ '@effect/platform-node-shared': 0.39.16(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ effect: 3.16.8+ multipasta: 0.2.5+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ '@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/cluster': 0.39.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])+ '@effect/platform': 0.84.11([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ '@parcel/watcher': 2.5.1+ effect: 3.16.8+ multipasta: 0.2.5+ ws: 8.18.2+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ '@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/cluster': 0.39.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])+ '@effect/platform': 0.84.11([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ '@parcel/watcher': 2.5.1+ effect: 3.16.8+ multipasta: 0.2.5+ ws: 8.18.2+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ '@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/cluster': 0.39.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])+ '@effect/platform': 0.84.11([email protected])+ '@effect/platform-node-shared': 0.40.2(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ effect: 3.16.8+ mime: 3.0.0+ undici: 7.10.0+ ws: 8.18.2+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ '@effect/[email protected]([email protected])':+ dependencies:+ effect: 3.16.8+ find-my-way-ts: 0.1.5+ msgpackr: 1.11.4+ multipasta: 0.2.5++ dependencies:+ '@effect/typeclass': 0.35.8([email protected])+ effect: 3.16.8++ dependencies:+ '@effect/typeclass': 0.35.8([email protected])+ effect: 3.16.8++ dependencies:+ '@effect/platform': 0.84.11([email protected])+ effect: 3.16.8++ '@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])':+ dependencies:+ '@effect/platform': 0.84.11([email protected])+ '@opentelemetry/semantic-conventions': 1.34.0+ effect: 3.16.8+ uuid: 11.1.0++ '@effect/[email protected]([email protected])':+ dependencies:+ effect: 3.16.8++ '@effect/[email protected]([email protected])([email protected](@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected]))':+ dependencies:+ effect: 3.16.8+ vitest: 3.2.4(@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected])++ '@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected])':+ dependencies:+ '@effect/platform': 0.84.11([email protected])+ effect: 3.16.8++ '@emnapi/[email protected]':+ dependencies:+ tslib: 2.8.1+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true'@esbuild/[email protected]':optional: true@@ -6394,7 +7072,7 @@ snapshots:globby: 11.1.0read-yaml-file: 1.1.0+ '@mastra/[email protected]([email protected])([email protected])([email protected])([email protected])':dependencies:'@ai-sdk/provider': 1.1.3'@ai-sdk/provider-utils': 2.2.8([email protected])@@ -6419,7 +7097,7 @@ snapshots:date-fns: 3.6.0dotenv: 16.5.0hono: 4.7.11json-schema: 0.4.0json-schema-to-zod: 2.6.1pino: 9.7.0@@ -6470,6 +7148,24 @@ snapshots:transitivePeerDependencies:- supports-color+ '@msgpackr-extract/[email protected]':+ optional: true++ '@msgpackr-extract/[email protected]':+ optional: true++ '@msgpackr-extract/[email protected]':+ optional: true++ '@msgpackr-extract/[email protected]':+ optional: true++ '@msgpackr-extract/[email protected]':+ optional: true++ '@msgpackr-extract/[email protected]':+ optional: true+'@next/[email protected]': {}'@next/[email protected]':@@ -7244,6 +7940,66 @@ snapshots:'@opentelemetry/api': 1.9.0'@opentelemetry/core': 2.0.1(@opentelemetry/[email protected])+ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ optional: true++ '@parcel/[email protected]':+ dependencies:+ detect-libc: 1.0.3+ is-glob: 4.0.3+ micromatch: 4.0.8+ node-addon-api: 7.1.1+ optionalDependencies:+ '@parcel/watcher-android-arm64': 2.5.1+ '@parcel/watcher-darwin-arm64': 2.5.1+ '@parcel/watcher-darwin-x64': 2.5.1+ '@parcel/watcher-freebsd-x64': 2.5.1+ '@parcel/watcher-linux-arm-glibc': 2.5.1+ '@parcel/watcher-linux-arm-musl': 2.5.1+ '@parcel/watcher-linux-arm64-glibc': 2.5.1+ '@parcel/watcher-linux-arm64-musl': 2.5.1+ '@parcel/watcher-linux-x64-glibc': 2.5.1+ '@parcel/watcher-linux-x64-musl': 2.5.1+ '@parcel/watcher-win32-arm64': 2.5.1+ '@parcel/watcher-win32-ia32': 2.5.1+ '@parcel/watcher-win32-x64': 2.5.1+'@pkgjs/[email protected]':optional: true@@ -7689,6 +8445,8 @@ snapshots:'@smithy/types': 4.3.1tslib: 2.8.1+ '@standard-schema/[email protected]': {}+'@swc/[email protected]': {}'@swc/[email protected]':@@ -7697,6 +8455,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:bun-types: 1.2.16@@ -7920,13 +8680,21 @@ snapshots:chai: 5.2.0tinyrainbow: 2.0.0- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]':+ dependencies:+ '@types/chai': 5.2.2+ '@vitest/spy': 3.2.4+ '@vitest/utils': 3.2.4+ chai: 5.2.0+ tinyrainbow: 2.0.0++ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 3.2.3estree-walker: 3.0.3magic-string: 0.30.17optionalDependencies:'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':dependencies:@@ -7944,26 +8712,62 @@ snapshots:optionalDependencies:+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 3.2.3+ estree-walker: 3.0.3+ magic-string: 0.30.17+ optionalDependencies:++ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 3.2.4+ estree-walker: 3.0.3+ magic-string: 0.30.17+ optionalDependencies:+'@vitest/[email protected]':dependencies:tinyrainbow: 2.0.0+ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 2.0.0+'@vitest/[email protected]':dependencies:'@vitest/utils': 3.2.3pathe: 2.0.3strip-literal: 3.0.0+ '@vitest/[email protected]':+ dependencies:+ '@vitest/utils': 3.2.4+ pathe: 2.0.3+ strip-literal: 3.0.0+'@vitest/[email protected]':dependencies:'@vitest/pretty-format': 3.2.3magic-string: 0.30.17pathe: 2.0.3+ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.4+ magic-string: 0.30.17+ pathe: 2.0.3+'@vitest/[email protected]':dependencies:tinyspy: 4.0.3+ '@vitest/[email protected]':+ dependencies:+ tinyspy: 4.0.3+'@vitest/[email protected]([email protected])':dependencies:'@vitest/utils': 3.2.3@@ -7973,7 +8777,7 @@ snapshots:sirv: 3.0.1tinyglobby: 0.2.14tinyrainbow: 2.0.0- vitest: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ vitest: 3.2.3(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])'@vitest/[email protected]':dependencies:@@ -7981,6 +8785,12 @@ snapshots:loupe: 3.1.3tinyrainbow: 2.0.0+ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.4+ loupe: 3.1.4+ tinyrainbow: 2.0.0+dependencies:event-target-shim: 5.0.1@@ -8069,6 +8879,8 @@ snapshots:+ [email protected]: {}+@@ -8298,6 +9110,14 @@ snapshots:+ dependencies:+ array-timsort: 1.0.3+ core-util-is: 1.0.3+ esprima: 4.0.1+ has-own-prop: 2.0.0+ repeat-string: 1.6.1+[email protected](@ai-sdk/[email protected]([email protected]))(@cloudflare/[email protected])(@langchain/[email protected]([email protected]([email protected])([email protected])))(@langchain/[email protected](@langchain/[email protected]([email protected]([email protected])([email protected])))([email protected]))([email protected]([email protected])([email protected]))([email protected](@langchain/[email protected]([email protected]([email protected])([email protected])))([email protected])([email protected]([email protected])([email protected]))([email protected]))([email protected]([email protected])([email protected])):dependencies:'@ai-sdk/openai': 1.3.22([email protected])@@ -8356,6 +9176,12 @@ snapshots:+ dependencies:+ is-what: 4.1.16++ [email protected]: {}+dependencies:object-assign: 4.1.1@@ -8367,6 +9193,10 @@ snapshots:shebang-command: 2.0.0which: 2.0.2+ dependencies:+ type-fest: 1.4.0+@@ -8401,6 +9231,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -8430,6 +9262,23 @@ snapshots:+ [email protected](ff5edfb43a1891ed491370151a2c33b9):+ dependencies:+ '@effect/cluster': 0.39.2(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected])+ '@effect/platform': 0.84.11([email protected])+ '@effect/platform-node': 0.86.2(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))([email protected]))([email protected]))(@effect/[email protected]([email protected]))(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected](@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected]))([email protected])+ '@effect/sql': 0.38.1(@effect/[email protected](@effect/[email protected]([email protected]))([email protected]))(@effect/[email protected]([email protected]))([email protected])+ comment-json: 4.2.5+ effect: 3.16.8+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ '@standard-schema/spec': 1.0.0+ fast-check: 3.23.2+@@ -8697,10 +9546,16 @@ snapshots:iconv-lite: 0.4.24tmp: 0.0.33+ dependencies:+ pure-rand: 6.1.0++ [email protected]: {}+dependencies:'@nodelib/fs.stat': 2.0.5@@ -8764,6 +9619,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:locate-path: 5.0.0@@ -8953,6 +9810,8 @@ snapshots:+ [email protected]: {}+@@ -8965,11 +9824,12 @@ snapshots:dependencies:json-schema-walker: 2.0.0openapi-types: 12.1.3optionalDependencies:+ effect: 3.16.8hono: 4.7.11zod: 3.25.62@@ -9028,8 +9888,12 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:'@inquirer/core': 9.2.1@@ -9084,6 +9948,8 @@ snapshots:dependencies:better-path-resolve: 1.0.0+ [email protected]: {}+@@ -9287,6 +10153,8 @@ snapshots:+ [email protected]: {}+@@ -9341,6 +10209,8 @@ snapshots:+ [email protected]: {}+@@ -9374,6 +10244,24 @@ snapshots:+ dependencies:+ node-gyp-build-optional-packages: 5.2.2+ optionalDependencies:+ '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.3+ '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.3+ '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.3+ '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.3+ '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.3+ '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.3+ optional: true++ optionalDependencies:+ msgpackr-extract: 3.0.3++ [email protected]: {}+@@ -9418,12 +10306,19 @@ snapshots:- '@babel/core'- babel-plugin-macros+ [email protected]: {}+dependencies:whatwg-url: 5.0.0+ dependencies:+ detect-libc: 2.0.4+ optional: true+@@ -9693,6 +10588,15 @@ snapshots:tsx: 4.20.1yaml: 2.8.0+ dependencies:+ lilconfig: 3.1.3+ optionalDependencies:+ jiti: 1.21.7+ postcss: 8.5.5+ tsx: 4.20.3+ yaml: 2.8.0+dependencies:postcss: 8.5.5@@ -9729,6 +10633,10 @@ snapshots:+ dependencies:+ fast-diff: 1.3.0+@@ -9768,6 +10676,8 @@ snapshots:+ [email protected]: {}+dependencies:tweetnacl: 1.0.3@@ -9848,6 +10758,8 @@ snapshots:+ [email protected]: {}+@@ -10203,6 +11115,10 @@ snapshots:- supports-color- utf-8-validate+ dependencies:+ copy-anything: 3.0.5+dependencies:has-flag: 4.0.0@@ -10242,6 +11158,15 @@ snapshots:transitivePeerDependencies:- ts-node+ [email protected]: {}++ dependencies:+ is-stream: 3.0.0+ temp-dir: 3.0.0+ type-fest: 2.19.0+ unique-string: 3.0.0+@@ -10269,6 +11194,8 @@ snapshots:+ [email protected]: {}+@@ -10283,6 +11210,8 @@ snapshots:+ [email protected]: {}+@@ -10331,6 +11260,34 @@ snapshots:- tsx- yaml+ [email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ bundle-require: 5.1.0([email protected])+ cac: 6.7.14+ chokidar: 4.0.3+ consola: 3.4.2+ debug: 4.4.1+ esbuild: 0.25.5+ fix-dts-default-cjs-exports: 1.0.1+ joycon: 3.1.1+ picocolors: 1.1.1+ postcss-load-config: 6.0.1([email protected])([email protected])([email protected])([email protected])+ resolve-from: 5.0.0+ rollup: 4.43.0+ source-map: 0.8.0-beta.0+ sucrase: 3.35.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.14+ tree-kill: 1.2.2+ optionalDependencies:+ postcss: 8.5.5+ typescript: 5.8.3+ transitivePeerDependencies:+ - jiti+ - supports-color+ - tsx+ - yaml+dependencies:esbuild: 0.25.5@@ -10338,6 +11295,13 @@ snapshots:optionalDependencies:fsevents: 2.3.3+ dependencies:+ esbuild: 0.25.5+ get-tsconfig: 4.10.1+ optionalDependencies:+ fsevents: 2.3.3+optional: true@@ -10373,6 +11337,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:media-typer: 0.3.0@@ -10423,6 +11391,12 @@ snapshots:+ [email protected]: {}++ dependencies:+ crypto-random-string: 4.0.0+@@ -10449,13 +11423,13 @@ snapshots:- [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14debug: 4.4.1es-module-lexer: 1.7.0pathe: 2.0.3transitivePeerDependencies:- '@types/node'- jiti@@ -10512,7 +11486,49 @@ snapshots:- tsx- yaml- [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ cac: 6.7.14+ debug: 4.4.1+ es-module-lexer: 1.7.0+ pathe: 2.0.3+ transitivePeerDependencies:+ - '@types/node'+ - jiti+ - less+ - lightningcss+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ cac: 6.7.14+ debug: 4.4.1+ es-module-lexer: 1.7.0+ pathe: 2.0.3+ transitivePeerDependencies:+ - '@types/node'+ - jiti+ - less+ - lightningcss+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):dependencies:esbuild: 0.25.5fdir: 6.4.6([email protected])@@ -10524,7 +11540,7 @@ snapshots:'@types/node': 20.19.1fsevents: 2.3.3jiti: 1.21.7- tsx: 4.20.1+ tsx: 4.20.3yaml: 2.8.0[email protected](@types/[email protected])([email protected])([email protected])([email protected]):@@ -10557,11 +11573,26 @@ snapshots:tsx: 4.20.1yaml: 2.8.0- [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ esbuild: 0.25.5+ fdir: 6.4.6([email protected])+ picomatch: 4.0.2+ postcss: 8.5.5+ rollup: 4.43.0+ tinyglobby: 0.2.14+ optionalDependencies:+ '@types/node': 24.0.3+ fsevents: 2.3.3+ jiti: 1.21.7+ tsx: 4.20.3+ yaml: 2.8.0++ [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected]):dependencies:'@types/chai': 5.2.2'@vitest/expect': 3.2.3- '@vitest/mocker': 3.2.3([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ '@vitest/mocker': 3.2.3([email protected](@types/[email protected])([email protected])([email protected])([email protected]))'@vitest/pretty-format': 3.2.3'@vitest/runner': 3.2.3'@vitest/snapshot': 3.2.3@@ -10579,8 +11610,8 @@ snapshots:tinyglobby: 0.2.14tinypool: 1.1.0tinyrainbow: 2.0.0- vite-node: 3.2.3(@types/[email protected])([email protected])([email protected])([email protected])+ vite-node: 3.2.3(@types/[email protected])([email protected])([email protected])([email protected])why-is-node-running: 2.3.0optionalDependencies:'@types/node': 20.19.1@@ -10683,6 +11714,90 @@ snapshots:- tsx- yaml+ [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ '@types/chai': 5.2.2+ '@vitest/expect': 3.2.3+ '@vitest/mocker': 3.2.3([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 3.2.3+ '@vitest/runner': 3.2.3+ '@vitest/snapshot': 3.2.3+ '@vitest/spy': 3.2.3+ '@vitest/utils': 3.2.3+ chai: 5.2.0+ debug: 4.4.1+ expect-type: 1.2.1+ magic-string: 0.30.17+ pathe: 2.0.3+ picomatch: 4.0.2+ std-env: 3.9.0+ tinybench: 2.9.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.14+ tinypool: 1.1.0+ tinyrainbow: 2.0.0+ vite-node: 3.2.3(@types/[email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/node': 24.0.3+ '@vitest/ui': 3.2.3([email protected])+ transitivePeerDependencies:+ - jiti+ - less+ - lightningcss+ - msw+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ [email protected](@types/[email protected])(@vitest/[email protected]([email protected]))([email protected])([email protected])([email protected]):+ dependencies:+ '@types/chai': 5.2.2+ '@vitest/expect': 3.2.4+ '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 3.2.4+ '@vitest/runner': 3.2.4+ '@vitest/snapshot': 3.2.4+ '@vitest/spy': 3.2.4+ '@vitest/utils': 3.2.4+ chai: 5.2.0+ debug: 4.4.1+ expect-type: 1.2.1+ magic-string: 0.30.17+ pathe: 2.0.3+ picomatch: 4.0.2+ std-env: 3.9.0+ tinybench: 2.9.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.14+ tinypool: 1.1.1+ tinyrainbow: 2.0.0+ vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/node': 24.0.3+ '@vitest/ui': 3.2.3([email protected])+ transitivePeerDependencies:+ - jiti+ - less+ - lightningcss+ - msw+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 39bdfc9d1..40822acc2 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,7 +1,9 @@packages:- "ts/packages/core"+ - "ts/packages/cli"- "ts/packages/json-schema-to-zod"- "ts/packages/providers/*"+ - "ts/packages/ts-builders"- "ts/packages/wrappers/*"- "ts/examples/*"- "fern"diff --git a/ts/packages/cli/.gitignore b/ts/packages/cli/.gitignorenew file mode 100644index 000000000..c2a67776e--- /dev/null+++ b/ts/packages/cli/.gitignore@@ -0,0 +1,3 @@+.generated/+.composio/+composiodiff --git a/ts/packages/cli/README.md b/ts/packages/cli/README.mdnew file mode 100644index 000000000..b57fdd840--- /dev/null+++ b/ts/packages/cli/README.md@@ -0,0 +1,96 @@+# @composio/cli++> A tool for managing Composio.dev projects in Python and TypeScript.++This package defines the Composio CLI used to interact with the Composio Platform. It provides a powerful and flexible way to manage and execute tools, handle authentication, and integrate with various platforms and frameworks.++## Overview++The CLI is build using:++- [TypeScript](https://www.typescriptlang.org/)+- [The Effect ecosystem](https://effect.website/docs)+- [Bun](https://bun.sh/)+- [Vitest](https://vitest.dev/)++## 🧑💻 Usage++```+composio [--log-level all|trace|debug|info|warning|error|fatal|none]+```++### Optional Flags++- `--log-level`: Set the log verbosity level. Accepted values: all, trace, debug, info, warning, error, fatal, none++## 🧭 Commands++| Command | Description | Status |+| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |+| `composio version` | Display the current CLI version. | ✅ |+| `composio whoami` | Show the currently logged-in user/account. | ✅ It displays the local API_KEY, or shows a message if no API_KEY is found. |+| `composio login` | Log in to the Composio SDK. | ⏰ The session client is defined, but the authentication workflow is currently incomplete |+| `composio generate [-o, --output-dir <directory>]` | Auto-detect the project language (Python or TypeScript) and generate the latest app type stubs. | ✅ |+| `composio py` | Python project-specific commands. |+| `composio py generate [-o, --output-dir <directory>]` | Generate updated Python stubs with the latest app data. | ✅ |+| `composio ts` | TypeScript project-specific commands. | ✅ |+| `composio ts generate [-o, --output-dir <directory>] [--single-file]` | Generate updated TypeScript stubs, optionally as a single file. | ✅ |+| `composio upgrade` | Self-update the Composio CLI if a new release is out. | 🛑 Not implemented yet |++## Configuration++The Composio CLI supports configuration via environment variables and a JSON configuration file.++The Composio CLI also supports a JSON configuration file. The default location is `~/.composio/user_data.json`, but you can specify a custom location using the `COMPOSIO_CACHE_DIR` environment variable.++| Environment Variable | User JSON config | Description | Default |+| ---------------------- | ---------------- | ------------------------------------------------------------------ | ------- |+| COMPOSIO_API_KEY | `api_key` | Your Composio API key | None |+| COMPOSIO_BASE_URL | `base_url` | The base URL of the Composio backend API | None |+| COMPOSIO_CACHE_DIR | `cache_dir` | The directory where the Composio CLI stores cache files | None |+| COMPOSIO_LOG_LEVEL | `log_level` | The log level for the Composio CLI | None |+| DEBUG_OVERRIDE_VERSION | `version` | The version to use when upgrading the Composio CLI (for debugging) | None |++## Development++### Installation++```bash+pnpm install+```++### Build TypeScript code++```bash+pnpm build+```++### Build self-contained executable++```bash+pnpm build:bin+```++or++```bash+bun run ./scripts/build-binary.ts+```++### Run interactively++```bash+pnpm cli+```++For instance, to generate type stubs for a TypeScript project, you can run:++```bash+pnpm cli ts generate+```++### Test++```bash+pnpm test+```diff --git a/ts/packages/cli/eslint.config.mjs b/ts/packages/cli/eslint.config.mjsnew file mode 100644index 000000000..691e8dae9--- /dev/null+++ b/ts/packages/cli/eslint.config.mjs@@ -0,0 +1,6 @@+export default {+ extends: ['../../eslint.config.mjs'],+ rules: {+ '@effect/eslint-plugin': 'error',+ },+};diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.jsonnew file mode 100644index 000000000..035f0d753--- /dev/null+++ b/ts/packages/cli/package.json@@ -0,0 +1,67 @@+{+ "name": "@composio/cli",+ "version": "0.1.24",+ "description": "Composio CLI",+ "main": "dist/bin.js",+ "bin": {+ "composio": "./dist/composio"+ },+ "type": "module",+ "repository": {+ "type": "git",+ "url": "https://github.com/ComposioHQ/composio.git",+ "directory": "ts/packages/cli"+ },+ "publishConfig": {+ "access": "public",+ "main": "dist/bin.js",+ "types": "dist/bin.d.ts"+ },+ "files": [+ "README.md",+ "dist"+ ],+ "scripts": {+ "cli": "bun run src/bin.ts",+ "build:bin": "bun run ./scripts/build-binary.ts",+ "build": "tsup",+ "bin": "./dist/composio",+ "test": "vitest run",+ "prepublishOnly": "pnpm build && pnpm build:bin"+ },+ "keywords": [+ "composio",+ "mcp",+ "cli"+ ],+ "author": "Alberto Schiabel <[email protected]> (https://github.com/jkomyno)",+ "license": "ISC",+ "packageManager": "[email protected]",+ "devDependencies": {+ "@effect/eslint-plugin": "^0.3.2",+ "@effect/platform": "^0.84.11",+ "@effect/vitest": "^0.23.8",+ "@types/bun": "^1.2.16",+ "@types/semver": "^7.7.0",+ "tempy": "^3.1.0",+ "tsup": "^8.5.0",+ "tsx": "^4.20.3",+ "typescript": "^5.8.3",+ "vitest": "^3.2.4"+ },+ "dependencies": {+ "@composio/client": "0.1.0-alpha.17",+ "@composio/core": "workspace:*",+ "@composio/ts-builders": "workspace:*",+ "@effect/cli": "^0.63.11",+ "@effect/platform-bun": "^0.69.16",+ "@effect/platform-node-shared": "^0.40.2",+ "chalk": "^5.4.1",+ "effect": "^3.16.8",+ "effect-errors": "^1.10.11",+ "indent-string": "^5.0.0",+ "semver": "^7.7.2",+ "superjson": "^2.2.2"+ },+ "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064"+}diff --git a/ts/packages/cli/scripts/build-binary.ts b/ts/packages/cli/scripts/build-binary.tsnew file mode 100644index 000000000..20b903a9f--- /dev/null+++ b/ts/packages/cli/scripts/build-binary.ts@@ -0,0 +1,111 @@+import process from 'node:process';+import {+ Cause,+ Config,+ ConfigProvider,+ Console,+ Effect,+ Exit,+ Stream,+ Logger,+ Layer,+ LogLevel,+} from 'effect';+import { Command } from '@effect/platform';+import { BunContext, BunRuntime } from '@effect/platform-bun';+import type { Teardown } from '@effect/platform/Runtime';++export function buildBinary() {+ return Effect.gen(function* () {+ const cwd = process.cwd();+ yield* Effect.logDebug(`Building binary in ${cwd}`);++ const args = [+ 'bun',+ /**+ * Transpile and bundle the CLI app.+ */+ 'build',+ './src/bin.ts',++ /**+ * Statically inline any environment variable that matches `DEBUG_OVERRIDE_*`.+ */+ '--env',+ 'DEBUG_OVERRIDE_*',++ /**+ * Generate a standalone Bun executable containing your bundled code.+ */+ '--compile',+ '--production',++ /**+ * Output file destination.+ */+ '--outfile',+ './dist/composio',+ ] as const satisfies ReadonlyArray<string>;++ const cmd = Command.make(...args);++ yield* Effect.logDebug('Running build command with', args.join(' '), '');++ const { exitCode } = yield* cmd.pipe(+ Command.start,+ Effect.flatMap(process =>+ Effect.all(+ {+ exitCode: process.exitCode,+ output: Stream.merge(+ Stream.decodeText(process.stdout, 'utf-8'),+ Stream.decodeText(process.stderr, 'utf-8'),+ { haltStrategy: 'left' }+ ).pipe(+ Stream.tap(chunk => Console.log(chunk)),+ Stream.runDrain+ ),+ },+ {+ concurrency: 'unbounded',+ }+ )+ )+ );++ process.exitCode = exitCode;++ if (exitCode !== 0) {+ return yield* Effect.logInfo('Failed to build binary');+ }++ yield* Effect.logDebug('', 'Binary built successfully');+ });+}++export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {+ const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);+ const errorCode = Number(process.exitCode ?? 1);+ onExit(shouldFail ? errorCode : 0);+};++const ConfigLive = Effect.gen(function* () {+ const logLevel = yield* Config.logLevel('COMPOSIO_LOG_LEVEL').pipe(+ Config.withDefault(LogLevel.Info)+ );++ return Logger.minimumLogLevel(logLevel);+}).pipe(Layer.unwrapEffect, Layer.merge(Layer.setConfigProvider(ConfigProvider.fromEnv())));++if (require.main === module) {+ buildBinary().pipe(+ Effect.provide(ConfigLive),+ Effect.provide(Logger.pretty),+ Effect.provide(BunContext.layer),+ Effect.scoped,+ Effect.map(() => ({ message: 'Build process completed successfully.' })),+ BunRuntime.runMain({+ teardown,+ })+ );+}diff --git a/ts/packages/cli/src/bin.ts b/ts/packages/cli/src/bin.tsnew file mode 100644index 000000000..e321f423a--- /dev/null+++ b/ts/packages/cli/src/bin.ts@@ -0,0 +1,80 @@+import process from 'node:process';+import { Cause, Effect, Exit, Layer } from 'effect';+import { prettyPrint } from 'effect-errors';+import { CliConfig } from '@effect/cli';+import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';+import type { Teardown } from '@effect/platform/Runtime';+import { runWithConfig } from 'src/commands';+import * as constants from 'src/constants';+import { ComposioCliConfig } from 'src/cli-config';+import { UserConfigLive } from 'src/services/user-config';+import {+ ComposioSessionRepository,+ ComposioToolkitsRepository,+} from 'src/services/composio-clients';+import { NodeProcess } from 'src/services/node-process';+import { EnvLangDetector } from './services/env-lang-detector';++/**+ * Concrete Effect layer compositions for the Composio CLI runtime.+ *+ * ┌─── The service to be created+ * │ ┌─── The possible error+ * │ │ ┌─── The required dependencies+ * ▼ ▼ ▼+ * Layer<RequirementsOut, Error, RequirementsIn>+ */++/**+ * Service layer that reads the user config.+ */+export const UserConfigProviderLiveFromFs = Layer.provide(UserConfigLive, BunFileSystem.layer);++/**+ * Service layer that configures the CLI appearance and default command options.+ */+export const CliConfigLive = CliConfig.layer(ComposioCliConfig);++const layers = Layer.mergeAll(+ UserConfigProviderLiveFromFs,+ CliConfigLive.pipe(Layer.provide(UserConfigProviderLiveFromFs)),+ NodeProcess.Default,+ ComposioSessionRepository.Default.pipe(Layer.provide(UserConfigProviderLiveFromFs)),+ ComposioToolkitsRepository.Default.pipe(Layer.provide(UserConfigProviderLiveFromFs)),+ EnvLangDetector.Default,+ BunContext.layer,+ BunFileSystem.layer+);++export const teardown: Teardown = <E, A>(exit: Exit.Exit<E, A>, onExit: (code: number) => void) => {+ const shouldFail = Exit.isFailure(exit) && !Cause.isInterruptedOnly(exit.cause);+ const errorCode = Number(process.exitCode ?? 1);+ onExit(shouldFail ? errorCode : 0);+};++/**+ * CLI entrypoint, which:+ * - runs the Effect runtime and sets up its runtime environment+ * - collects and displays errors+ */+if (require.main === module) {+ const runWithArgs = Effect.flatMap(runWithConfig, run =>+ run(process.argv)+ ) satisfies Effect.Effect<void, unknown, unknown>;++ runWithArgs.pipe(+ Effect.provide(layers),+ Effect.provide(BunContext.layer),+ Effect.withSpan('composio-cli', {+ attributes: {+ name: constants.APP_NAME,+ filename: 'src/bin.ts',+ },+ }),+ Effect.sandbox,+ Effect.catchAll(e => Effect.fail(prettyPrint(e))),+ BunRuntime.runMain({+ teardown,+ })+ );+}diff --git a/ts/packages/cli/src/cli-config.ts b/ts/packages/cli/src/cli-config.tsnew file mode 100644index 000000000..d3ee6016d--- /dev/null+++ b/ts/packages/cli/src/cli-config.ts@@ -0,0 +1,7 @@+import type { CliConfig } from '@effect/cli/CliConfig';++export const ComposioCliConfig = {+ showBuiltIns: false,+ autoCorrectLimit: 0,+ isCaseSensitive: true,+} satisfies Partial<CliConfig>;diff --git a/ts/packages/cli/src/commands/$default.cmd.ts b/ts/packages/cli/src/commands/$default.cmd.tsnew file mode 100644index 000000000..63e6d57ca--- /dev/null+++ b/ts/packages/cli/src/commands/$default.cmd.ts@@ -0,0 +1,55 @@+import { Context, Schema, LogLevel, String, pipe, Layer, Effect } from 'effect';+import { Command, Options } from '@effect/cli';+import { setMinimumLogLevel } from 'src/effects/with-log-level';+import type { ConfigError } from 'effect/ConfigError';+import { versionCmd } from './version.cmd';++const logLevelChoices = LogLevel.allLevels.map(level => String.toLowerCase(level._tag));++const LogLevelLiteralSchema = Schema.Literal(...logLevelChoices)+ .annotations({+ identifier: 'LogLevelLiteral',+ })+ .pipe(+ Schema.transform(+ Schema.declare((input: unknown): input is LogLevel.LogLevel =>+ LogLevel.allLevels.includes(input as LogLevel.LogLevel)+ ).annotations({+ identifier: 'LogLevel',+ }),+ {+ decode: literal => pipe(literal, String.capitalize, LogLevel.fromLiteral),+ encode: logLevel => String.toLowerCase(logLevel._tag),+ strict: true,+ }+ )+ );++const logLevel = Options.choice('log-level', logLevelChoices).pipe(+ Options.withSchema(LogLevelLiteralSchema),+ Options.withDescription('Define log level'),+ Options.optional+);++class $DefaultCmdContext extends Context.Tag('cli/$DefaultCmdContext')<+ $DefaultCmdContext,+ Layer.Layer<never, ConfigError, never>+>() {}++/**+ * CLI entry point for the Composio CLI.+ *+ * @example+ * ```bash+ * composio <subcommand>+ * ```+ */+export const $defaultCmd = Command.make('composio', { logLevel }).pipe(+ Command.withSubcommands([versionCmd]),+ Command.withDescription(+ `Composio CLI - A tool for managing Python and TypeScript composio.dev projects.`+ ),+ Command.provideEffect($DefaultCmdContext, ({ logLevel }) =>+ Effect.succeed(setMinimumLogLevel(logLevel))+ )+);diff --git a/ts/packages/cli/src/commands/generate.cmd.ts b/ts/packages/cli/src/commands/generate.cmd.tsnew file mode 100644index 000000000..649049ee0--- /dev/null+++ b/ts/packages/cli/src/commands/generate.cmd.ts@@ -0,0 +1,44 @@+import { Command, Options } from '@effect/cli';+import { Effect, Console, Match } from 'effect';+import { EnvLangDetector } from 'src/services/env-lang-detector';+import { NodeProcess } from 'src/services/node-process';+import { generateTypescriptTypeStubs } from './ts/commands/ts.generate.cmd';+import { generatePythonTypeStubs } from './py/commands/py.generate.cmd';++export const outputOpt = Options.optional(+ Options.directory('output-dir', {+ exists: 'either',+ })+).pipe(Options.withAlias('o'), Options.withDescription('Output directory for type stubs'));++/**+ * @example+ * ```bash+ * composio generate <command>+ * ```+ */+export const generateCmd = Command.make('generate', { outputOpt }).pipe(+ Command.withDescription(+ 'Updates the local type stubs with the latest app data, automatically detecting the language of the project in the current working directory (TypeScript | Python).'+ ),+ Command.withHandler(({ outputOpt }) =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;++ yield* Effect.logDebug('Identifying project type...');+ const envLangDetector = yield* EnvLangDetector;+ const envLang = yield* envLangDetector.detectEnvLanguage(cwd);+ yield* Console.log(`Project type detected: ${envLang}`);++ // Redirect to either `ts generate` or `py generate` commands+ yield* Match.value(envLang).pipe(+ Match.when('TypeScript', () =>+ generateTypescriptTypeStubs({ outputOpt, singleFile: false })+ ),+ Match.when('Python', () => generatePythonTypeStubs({ outputOpt })),+ Match.exhaustive+ );+ })+ )+);diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.tsnew file mode 100644index 000000000..46f35b36e--- /dev/null+++ b/ts/packages/cli/src/commands/index.ts@@ -0,0 +1,31 @@+import { Effect } from 'effect';+import { Command } from '@effect/cli';+import * as constants from 'src/constants';+import { $defaultCmd } from './$default.cmd';+import { getVersion } from 'src/effects/version';+import { versionCmd } from './version.cmd';+import { whoamiCmd } from './whoami.cmd';+import { loginCmd } from './login.cmd';+import { pyCmd } from './py/py.cmd';+import { tsCmd } from './ts/ts.cmd';+import { generateCmd } from './generate.cmd';++const $cmd = $defaultCmd.pipe(+ Command.withSubcommands([versionCmd, whoamiCmd, loginCmd, generateCmd, pyCmd, tsCmd])+);++export const runWithConfig = Effect.gen(function* () {+ const version = yield* getVersion;++ return Command.run($cmd, {+ name: 'composio',+ executable: 'composio',+ version,+ });+});++export const run = Command.run($cmd, {+ name: 'composio',+ version: constants.APP_VERSION,+ executable: 'composio',+});diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.tsnew file mode 100644index 000000000..70ef312bb--- /dev/null+++ b/ts/packages/cli/src/commands/login.cmd.ts@@ -0,0 +1,25 @@+import { Command } from '@effect/cli';+import { Effect, Console } from 'effect';+import { ComposioSessionRepository } from 'src/services/composio-clients';++/**+ * CLI command to login using Composio's CLI session APIs.+ *+ * @example+ * ```bash+ * composio login <command>+ * ```+ */+export const loginCmd = Command.make('login', {}, () =>+ Effect.gen(function* () {+ const client = yield* ComposioSessionRepository;+ const session = yield* client.createSession();+ const linkedSession = yield* client.linkSession(session);++ yield* Effect.logDebug(`Linked session: ${JSON.stringify(linkedSession)}`);++ yield* Console.log(+ `Linked session code ${session.code} to user account ${linkedSession.account.email}`+ );+ })+).pipe(Command.withDescription('Log in to the Composio SDK.'));diff --git a/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts b/ts/packages/cli/src/commands/py/commands/py.generate.cmd.tsnew file mode 100644index 000000000..c21fbbcd3--- /dev/null+++ b/ts/packages/cli/src/commands/py/commands/py.generate.cmd.ts@@ -0,0 +1,65 @@+import path from 'node:path';+import { Command, Options } from '@effect/cli';+import { Console, Effect, Option } from 'effect';+import { FileSystem } from '@effect/platform';+import { ComposioToolkitsRepository } from 'src/services/composio-clients';+import type { GetCmdParams } from 'src/type-utils';+import { NodeProcess } from 'src/services/node-process';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { generatePythonToolkitSources } from 'src/generation/python/generate-toolkit-sources';++export const outputOpt = Options.optional(+ Options.directory('output-dir', {+ exists: 'either',+ })+).pipe(+ Options.withAlias('o'),+ Options.withDescription(+ 'Output directory for the generated Python type stubs (default: `./.generated/composio-py`)'+ )+);++const _pyCmd$Generate = Command.make('generate', { outputOpt }).pipe(+ Command.withDescription('Updates the local type stubs with the latest app data.')+);++export const pyCmd$Generate = _pyCmd$Generate.pipe(Command.withHandler(generatePythonTypeStubs));++export function generatePythonTypeStubs({ outputOpt }: GetCmdParams<typeof _pyCmd$Generate>) {+ return Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;++ const fs = yield* FileSystem.FileSystem;++ const output = outputOpt.pipe(+ Option.getOrElse(() => path.join(cwd, '.generated', 'composio-py'))+ );+ yield* fs.makeDirectory(output, { recursive: true });++ yield* Console.log('Fetching latest data from Composio API...');+ const client = yield* ComposioToolkitsRepository;++ yield* Effect.logDebug('Fetching toolkits...');+ const toolkits = yield* client.getToolkits();++ yield* Effect.logDebug('Fetching tools...');+ const tools = yield* client.getTools();++ yield* Effect.logDebug('Fetching trigger types...');+ const triggerTypes = yield* client.getTriggerTypes();++ const index = createToolkitIndex({ toolkits, tools, triggerTypes });+ const sourceFiles = generatePythonToolkitSources(index).map(+ ([filename, content]) => [path.join(output, filename), content] as const+ );++ yield* Console.log(`Writing type stubs to ${output}...`);++ yield* Effect.all(+ sourceFiles.map(([filePath, content]) => fs.writeFileString(filePath, content))+ );++ return yield* Console.log('✅ Type stubs generated successfully.');+ });+}diff --git a/ts/packages/cli/src/commands/py/py.cmd.ts b/ts/packages/cli/src/commands/py/py.cmd.tsnew file mode 100644index 000000000..bf8d6b7a1--- /dev/null+++ b/ts/packages/cli/src/commands/py/py.cmd.ts@@ -0,0 +1,15 @@+import { Command } from '@effect/cli';+import { pyCmd$Generate } from './commands/py.generate.cmd';++/**+ * CLI entry point for Python commands.+ *+ * @example+ * ```bash+ * composio py <command>+ * ```+ */+export const pyCmd = Command.make('py').pipe(+ Command.withDescription('Handle Python projects.'),+ Command.withSubcommands([pyCmd$Generate])+);diff --git a/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.tsnew file mode 100644index 000000000..cf406504f--- /dev/null+++ b/ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts@@ -0,0 +1,75 @@+import path from 'node:path';+import { Command, Options } from '@effect/cli';+import { Console, Effect, Option } from 'effect';+import { FileSystem } from '@effect/platform';+import { ComposioToolkitsRepository } from 'src/services/composio-clients';+import { NodeProcess } from 'src/services/node-process';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import type { GetCmdParams } from 'src/type-utils';+import { generateTypeScriptSources } from 'src/generation/typescript/generate';++export const outputOpt = Options.optional(+ Options.directory('output-dir', {+ exists: 'either',+ })+).pipe(+ Options.withAlias('o'),+ Options.withDescription(+ 'Output directory for the generated Python type stubs (default: `./.generated/composio-py`)'+ )+);++export const singleFile = Options.boolean('single-file').pipe(+ Options.withDefault(false),+ Options.withDescription('Emit a single TypeScript file')+);++const _tsCmd$Generate = Command.make('generate', { outputOpt, singleFile }).pipe(+ Command.withDescription('Updates the local type stubs with the latest app data.')+);++export const tsCmd$Generate = _tsCmd$Generate.pipe(+ Command.withHandler(generateTypescriptTypeStubs)+);++export function generateTypescriptTypeStubs({+ outputOpt,+ singleFile,+}: GetCmdParams<typeof _tsCmd$Generate>) {+ return Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;++ const fs = yield* FileSystem.FileSystem;++ const outputDir = outputOpt.pipe(+ Option.getOrElse(() => path.join(cwd, '.generated', 'composio-ts'))+ );+ yield* fs.makeDirectory(outputDir, { recursive: true });++ yield* Console.log('Fetching latest data from Composio API...');+ const client = yield* ComposioToolkitsRepository;++ yield* Effect.logDebug('Fetching toolkits...');+ const toolkits = yield* client.getToolkits();++ yield* Effect.logDebug('Fetching tools...');+ const tools = yield* client.getTools();++ yield* Effect.logDebug('Fetching trigger types...');+ const triggerTypes = yield* client.getTriggerTypes();++ const index = createToolkitIndex({ toolkits, tools, triggerTypes });+ const sources = generateTypeScriptSources({+ banner: 'Auto-generated by Composio CLI. Do not modify manually.',+ emitSingleFile: singleFile,+ outputDir,+ })(index);++ yield* Console.log(`Writing type stubs to ${outputDir}...`);++ yield* Effect.all(sources.map(([filePath, content]) => fs.writeFileString(filePath, content)));++ return yield* Console.log('✅ Type stubs generated successfully.');+ });+}diff --git a/ts/packages/cli/src/commands/ts/ts.cmd.ts b/ts/packages/cli/src/commands/ts/ts.cmd.tsnew file mode 100644index 000000000..2a5fee9f8--- /dev/null+++ b/ts/packages/cli/src/commands/ts/ts.cmd.ts@@ -0,0 +1,15 @@+import { Command } from '@effect/cli';+import { tsCmd$Generate } from './commands/ts.generate.cmd';++/**+ * CLI entry point for TypeScript commands.+ *+ * @example+ * ```bash+ * composio ts <command>+ * ```+ */+export const tsCmd = Command.make('ts').pipe(+ Command.withDescription('Handle TypeScript projects.'),+ Command.withSubcommands([tsCmd$Generate])+);diff --git a/ts/packages/cli/src/commands/version.cmd.ts b/ts/packages/cli/src/commands/version.cmd.tsnew file mode 100644index 000000000..dbcc2b073--- /dev/null+++ b/ts/packages/cli/src/commands/version.cmd.ts@@ -0,0 +1,23 @@+import { Command } from '@effect/cli';+import { Effect, Console } from 'effect';+import { getVersion } from 'src/effects/version';++/**+ * CLI command to display the version of the Composio CLI.+ *+ * @example+ * ```bash+ * composio version+ * ```+ */+export const versionCmd = Command.make('version', {}).pipe(+ Command.withDescription('Display your account information.'),+ Command.withHandler(() =>+ Effect.gen(function* () {+ const version = yield* getVersion;+ yield* Console.log(`${version}`);++ yield* Effect.logDebug('Composio CLI version command executed successfully.');+ })+ )+);diff --git a/ts/packages/cli/src/commands/whoami.cmd.ts b/ts/packages/cli/src/commands/whoami.cmd.tsnew file mode 100644index 000000000..a90e15b84--- /dev/null+++ b/ts/packages/cli/src/commands/whoami.cmd.ts@@ -0,0 +1,21 @@+import { Command } from '@effect/cli';+import { Effect, Console } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';++/**+ * CLI command to display your account information.+ *+ * @example+ * ```bash+ * composio whoami <command>+ * ```+ */+export const whoamiCmd = Command.make('whoami', {}).pipe(+ Command.withDescription('Display your account information.'),+ Command.withHandler(() =>+ Effect.gen(function* () {+ const apiKey = yield* APP_CONFIG['API_KEY'];+ yield* Console.log(`API KEY: ${apiKey}`);+ })+ )+);diff --git a/ts/packages/cli/src/constants.ts b/ts/packages/cli/src/constants.tsnew file mode 100644index 000000000..c4e27eb64--- /dev/null+++ b/ts/packages/cli/src/constants.ts@@ -0,0 +1,51 @@+import { constants } from '@composio/core';+import pkg from '../package.json' with { type: 'json' };++/**+ * Prefix for user environment variable keys used by the Composio CLI.+ */+export const APP_ENV_CONFIG_KEY_PREFIX = 'COMPOSIO_';++/**+ * Prefix for environment variable keys used by the Composio CLI for debug overrides.+ */+export const DEBUG_OVERRIDE_ENV_CONFIG_KEY_PREFIX = 'DEBUG_OVERRIDE_';++/**+ * Name of the user config file used by the Composio CLI.+ */+export const USER_CONFIG_FILE_NAME = constants.USER_DATA_FILE_NAME;++/**+ * Name of the directory used to store the Composio CLI config.+ */+export const USER_COMPOSIO_DIR = constants.COMPOSIO_DIR;++/**+ * A map of cache filenames used by the Composio CLI.+ */+export const CACHE_FILENAMES = {+ SESSION: 'session.json',+ TOOLKITS: 'toolkits.json',+ TOOLS: 'tools.json',+ TRIGGER_TYPES: 'trigger-types.json',+};++/**+ * Version of the Composio CLI, read from `package.json` at build time.+ */+export const APP_VERSION = pkg.version;++/**+ * Name of the Composio CLI application, read from `package.json` at build time.+ */+export const APP_NAME = pkg.name;++/**+ * GitHub repository information for release fetching+ */+export const GITHUB_REPO = {+ OWNER: 'ComposioHQ',+ REPO: 'composio',+ API_BASE_URL: 'https://api.github.com',+} as const;diff --git a/ts/packages/cli/src/effects/app-config.ts b/ts/packages/cli/src/effects/app-config.tsnew file mode 100644index 000000000..459c01e17--- /dev/null+++ b/ts/packages/cli/src/effects/app-config.ts@@ -0,0 +1,27 @@+import { Config, LogLevel, Option } from 'effect';++type APP_CONFIG = Config.Config.Wrap<{+ API_KEY: string;+ BASE_URL: Option.Option<string>;+ CACHE_DIR: Option.Option<string>;+ LOG_LEVEL: Option.Option<LogLevel.LogLevel>;+}>;++/**+ * Describe every configuration key used at runtime.+ * Keys are read from environment variables (with the `${APP_ENV_CONFIG_KEY_PREFIX}_<key>` format),+ * or from the user config file (in JSON format).+ */+export const APP_CONFIG = {+ // The API key for the Composio API+ API_KEY: Config.string('API_KEY'),++ // The base URL for the Composio API+ BASE_URL: Config.option(Config.string('BASE_URL')),++ // The cache directory for the Composio CLI+ CACHE_DIR: Config.option(Config.string('CACHE_DIR')),++ // The log level for the Composio CLI+ LOG_LEVEL: Config.option(Config.logLevel('LOG_LEVEL')),+} satisfies APP_CONFIG;diff --git a/ts/packages/cli/src/effects/debug-config.ts b/ts/packages/cli/src/effects/debug-config.tsnew file mode 100644index 000000000..7bdaa796d--- /dev/null+++ b/ts/packages/cli/src/effects/debug-config.ts@@ -0,0 +1,20 @@+import { Config, Option } from 'effect';++type DEBUG_CONFIG = Config.Config.Wrap<{+ UPGRADE_TARGET: Option.Option<string>;+ VERSION: Option.Option<string>;+}>;++/**+ * Describe debug configuration keys used at runtime.+ * Keys are read from environment variables (with the `DEBUG_OVERRIDE_<key>` format),+ * or from the user config file (in JSON format).+ */+export const DEBUG_OVERRIDE_CONFIG = {+ // The local binary used when upgrading the Composio CLI (for debugging).+ // When set, the upgrade command will use this local file instead of downloading from GitHub.+ UPGRADE_TARGET: Config.option(Config.string('DEBUG_OVERRIDE_UPGRADE_TARGET')),++ // The version to use when upgrading the Composio CLI (for debugging).+ VERSION: Config.option(Config.string('DEBUG_OVERRIDE_VERSION')),+} satisfies DEBUG_CONFIG;diff --git a/ts/packages/cli/src/effects/from-lazy-json.ts b/ts/packages/cli/src/effects/from-lazy-json.tsnew file mode 100644index 000000000..566d0f2a3--- /dev/null+++ b/ts/packages/cli/src/effects/from-lazy-json.ts@@ -0,0 +1,203 @@+import { FileSystem, Error as PlatformError } from '@effect/platform';+import {+ pipe,+ Array,+ Option,+ Effect,+ Cause,+ RegExp as regexp,+ Config,+ ConfigError,+ ConfigProvider,+ ConfigProviderPathPatch,+ HashSet,+} from 'effect';+import { JSONParse, JSONParseError } from 'src/effects/json';++/**+ * Lazy version of a `effect/ConfigProvider` that reads config values from a JSON file.+ */+export const configProviderFromLazyJson = (filePath: string) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;++ const { pathDelim, seqDelim } = { seqDelim: ',', pathDelim: '.' };+ const makePathString = (path: ReadonlyArray<string>): string =>+ pipe(path, Array.join(pathDelim));+ const unmakePathString = (pathString: string): ReadonlyArray<string> =>+ pathString.split(pathDelim);++ const STR_INDEX_REGEX = /(^.+)(\[(\d+)\])$/;++ const parseInteger = (str: string): Option.Option<number> => {+ const parsedIndex = Number.parseInt(str);+ return Number.isNaN(parsedIndex) ? Option.none() : Option.some(parsedIndex);+ };++ const splitIndexFrom = (key: string): Option.Option<[string, number]> => {+ const match = key.match(STR_INDEX_REGEX);+ if (match !== null) {+ const matchedString = match[1];+ const matchedIndex = match[3];+ const optionalString =+ matchedString !== undefined && matchedString.length > 0+ ? Option.some(matchedString)+ : Option.none();+ const optionalIndex = pipe(+ matchedIndex !== undefined && matchedIndex.length > 0+ ? Option.some(matchedIndex)+ : Option.none(),+ Option.flatMap(parseInteger)+ );+ return Option.all([optionalString, optionalIndex]);+ }+ return Option.none();+ };++ const splitIndexInKeys = (+ map: Map<string, string>,+ unmakePathString: (str: string) => ReadonlyArray<string>,+ makePathString: (chunk: ReadonlyArray<string>) => string+ ): Map<string, string> => {+ const newMap: Map<string, string> = new Map();+ for (const [pathString, value] of map) {+ const keyWithIndex = pipe(+ unmakePathString(pathString),+ Array.flatMap(key =>+ Option.match(splitIndexFrom(key), {+ onNone: () => Array.of(key),+ onSome: ([key, index]) => Array.make(key, `[${index}]`),+ })+ )+ );+ newMap.set(makePathString(keyWithIndex), value);+ }+ return newMap;+ };++ const parseConfig =+ <A>(_config: Config.Config<A>) =>+ (configContent: string) =>+ Effect.gen(function* () {+ const configContentAsJSON = yield* Effect.catchIf(+ JSONParse(configContent),+ (e): e is JSONParseError => e instanceof JSONParseError,+ e => Effect.fail(ConfigError.SourceUnavailable([], e.message, Cause.fail(e)))+ );++ const map = new Map(+ Object.entries(configContentAsJSON).map(([key, value]) => [key, String(value)] as const)+ );++ const mapWithIndexSplit = splitIndexInKeys(+ map,+ str => unmakePathString(str),+ makePathString+ );++ return mapWithIndexSplit;+ });++ const readConfig = <A>(filePath: string, config: Config.Config<A>) =>+ Effect.flatMap(fs.readFileString(filePath, 'utf-8'), parseConfig(config));++ const sourceError = (error: PlatformError.PlatformError) =>+ ConfigError.SourceUnavailable([], error.description ?? error.message, Cause.fail(error));++ const pathNotFoundError = ConfigError.MissingData([], `Path ${filePath} not found`);+ const handlePlatformError = (error: PlatformError.PlatformError) =>+ error._tag === 'SystemError' && error.reason === 'NotFound'+ ? Effect.fail(pathNotFoundError)+ : Effect.fail(sourceError(error));++ const splitPathString = (text: string, delim: string): Array<string> => {+ const split = text.split(new RegExp(`\\s*${regexp.escape(delim)}\\s*`));+ return split;+ };++ const parsePrimitive = <A>(+ text: string,+ path: ReadonlyArray<string>,+ primitive: Config.Config.Primitive<A>,+ delimiter: string,+ split: boolean+ ): Effect.Effect<Array<A>, ConfigError.ConfigError> => {+ if (!split) {+ return pipe(+ primitive.parse(text),+ Effect.mapBoth({+ onFailure: ConfigError.prefixed(Array.fromIterable(path)),+ onSuccess: Array.of,+ })+ );+ }+ return pipe(+ splitPathString(text, delimiter),+ Effect.forEach(char => primitive.parse(char.trim())),+ Effect.mapError(ConfigError.prefixed(Array.fromIterable(path)))+ );+ };++ const load = <A>(+ path: ReadonlyArray<string>,+ primitive: Config.Config.Primitive<A>,+ split = true+ ): Effect.Effect<Array<A>, ConfigError.ConfigError> =>+ Effect.gen(function* () {+ const mapWithIndexSplit = yield* Effect.catchIf(+ readConfig(filePath, primitive),+ PlatformError.isPlatformError,+ handlePlatformError+ );++ const pathString = makePathString(path);+ const valueOpt = mapWithIndexSplit.has(pathString)+ ? Option.some(mapWithIndexSplit.get(pathString)!)+ : Option.none();+ const value = yield* pipe(+ valueOpt,+ Effect.mapError(() =>+ ConfigError.MissingData(+ Array.fromIterable(path),+ `Expected ${pathString} to exist in the provided map`+ )+ )+ );++ return yield* parsePrimitive(value, path, primitive, seqDelim, split);+ });++ const enumerateChildren = (+ path: ReadonlyArray<string>+ ): Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError> =>+ Effect.gen(function* () {+ const mapWithIndexSplit = yield* Effect.catchIf(+ readConfig(filePath, Config.string()),+ PlatformError.isPlatformError,+ handlePlatformError+ );++ const keyPaths = Array.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString);+ const filteredKeyPaths = keyPaths+ .filter(keyPath => {+ for (let i = 0; i < path.length; i++) {+ const pathComponent = pipe(path, Array.unsafeGet(i));+ const currentElement = keyPath[i];+ if (currentElement === undefined || pathComponent !== currentElement) {+ return false;+ }+ }+ return true;+ })+ .flatMap(keyPath => keyPath.slice(path.length, path.length + 1));+ return HashSet.fromIterable(filteredKeyPaths);+ });++ return ConfigProvider.fromFlat(+ ConfigProvider.makeFlat({+ load,+ enumerateChildren,+ patch: ConfigProviderPathPatch.empty,+ })+ );+ });diff --git a/ts/packages/cli/src/effects/json.ts b/ts/packages/cli/src/effects/json.tsnew file mode 100644index 000000000..7c375ea30--- /dev/null+++ b/ts/packages/cli/src/effects/json.ts@@ -0,0 +1,12 @@+import { Data, Effect } from 'effect';++export class JSONParseError extends Data.TaggedError('effects/JSONParseError')<{+ readonly cause: Error;+ readonly message: string;+}> {}++export const JSONParse = (s: string) =>+ Effect.try({+ try: () => JSON.parse(s) as Record<string, unknown>,+ catch: e => new JSONParseError({ cause: e as Error, message: 'Failed to parse JSON' }),+ });diff --git a/ts/packages/cli/src/effects/setup-cache-dir.ts b/ts/packages/cli/src/effects/setup-cache-dir.tsnew file mode 100644index 000000000..02c34a7b9--- /dev/null+++ b/ts/packages/cli/src/effects/setup-cache-dir.ts@@ -0,0 +1,20 @@+import path from 'node:path';+import os from 'node:os';+import { Effect, pipe, Option } from 'effect';+import { FileSystem } from '@effect/platform';+import * as constants from 'src/constants';+import { APP_CONFIG } from 'src/effects/app-config';++// Helper to create cache directory+export const setupCacheDir = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;++ const cacheDir = yield* pipe(+ APP_CONFIG.CACHE_DIR,+ Effect.map(Option.getOrElse(() => path.join(os.homedir(), constants.USER_COMPOSIO_DIR)))+ );++ yield* fs.makeDirectory(cacheDir, { recursive: true });++ return cacheDir;+});diff --git a/ts/packages/cli/src/effects/version.ts b/ts/packages/cli/src/effects/version.tsnew file mode 100644index 000000000..a0687fd17--- /dev/null+++ b/ts/packages/cli/src/effects/version.ts@@ -0,0 +1,8 @@+import { Effect, Option } from 'effect';+import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';+import * as constants from 'src/constants';++export const getVersion = Effect.map(+ DEBUG_OVERRIDE_CONFIG.VERSION,+ Option.getOrElse(() => constants.APP_VERSION)+);diff --git a/ts/packages/cli/src/effects/with-log-level.ts b/ts/packages/cli/src/effects/with-log-level.tsnew file mode 100644index 000000000..576be5d04--- /dev/null+++ b/ts/packages/cli/src/effects/with-log-level.ts@@ -0,0 +1,16 @@+import { Effect, Option, Logger, LogLevel, Layer } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';++/**+ * Sets the minimum log level for subsequent logging operation, preferring the given log level,+ * and falling back to the one read from the config.+ */+export const setMinimumLogLevel = (logLevelFromCLI: Option.Option<LogLevel.LogLevel>) =>+ APP_CONFIG['LOG_LEVEL'].pipe(+ Effect.map(logLevelFromEnv => {+ return Option.zipLeft(logLevelFromCLI, logLevelFromEnv);+ }),+ Effect.map(Option.getOrElse(() => LogLevel.Info)),+ Effect.map(logLevel => Logger.minimumLogLevel(logLevel)),+ Layer.unwrapEffect+ );diff --git a/ts/packages/cli/src/generation/create-toolkit-index.ts b/ts/packages/cli/src/generation/create-toolkit-index.tsnew file mode 100644index 000000000..5a4dd1714--- /dev/null+++ b/ts/packages/cli/src/generation/create-toolkit-index.ts@@ -0,0 +1,87 @@+import { pipe, String, Record } from 'effect';+import type { Simplify } from 'effect/Types';+import { Toolkit, Toolkits, ToolkitName } from 'src/models/toolkits';+import { Tools } from 'src/models/tools';+import { TriggerTypes } from 'src/models/trigger-types';++const startsWith =+ <const P extends string>(prefix: P) =>+ (str: string): str is `${P}${string}` =>+ str.startsWith(prefix);++interface CreateToolkitIndexInput {+ toolkits: Toolkits; // e.g., [ { slug: 'gmail', }]+ tools: Tools; // e.g., [ 'GMAIL_SEND_EMAIL' ]+ triggerTypes: TriggerTypes; // e.g., [ 'GMAIL_NEW_EMAIL' ]+}++export type ToolkitIndexData = Simplify<{+ slug: string;+ tools: Record<`${ToolkitName}_${string}`, string>;+ triggerTypes: Record<`${ToolkitName}_${string}`, string>;+}>;++export type ToolkitIndex = Record<ToolkitName, ToolkitIndexData>;++/**+ * Creates a toolkit index from the given input.+ * Tools and triggerTypes are grouped by their corresponding toolkit name,+ * which is found by looking at the prefix of the tool or trigger type.+ */+export function createToolkitIndex(input: CreateToolkitIndexInput): Simplify<ToolkitIndex> {+ return pipe(+ input,+ groupByToolkits,+ Record.fromEntries,+ Record.mapEntries((value, key) => {+ const stripPrefix = String.slice(key.length + 1);++ const { slug } = value.toolkit;+ const tools = value.tools.map(tool => [stripPrefix(tool), tool] as const);+ const triggerTypes = value.triggerTypes.map(+ triggerType => [stripPrefix(triggerType), triggerType] as const+ );++ return [+ key,+ { slug, tools: Record.fromEntries(tools), triggerTypes: Record.fromEntries(triggerTypes) },+ ] as const;+ })+ );+}++type GroupByToolkitOutput<T extends ToolkitName> = [+ Uppercase<T>,+ {+ toolkit: Toolkit;+ tools: Array<`${Uppercase<T>}_${string}`>;+ triggerTypes: Array<`${Uppercase<T>}_${string}`>;+ },+];++const groupByToolkit =+ <const T extends string>(toolkit: Omit<Toolkit, 'name'> & { name: T }) =>+ ({+ tools,+ triggerTypes,+ }: Omit<CreateToolkitIndexInput, 'toolkits'>): GroupByToolkitOutput<T & ToolkitName> => {+ const toolkitName = pipe(toolkit.slug, String.toUpperCase, ToolkitName) as Uppercase<+ T & ToolkitName+ >;++ return [+ toolkitName,+ {+ toolkit,+ tools: tools.filter(startsWith(`${toolkitName}_`)),+ triggerTypes: triggerTypes.filter(startsWith(`${toolkitName}_`)),+ },+ ];+ };++function groupByToolkits({+ toolkits,+ ...rest+}: CreateToolkitIndexInput): GroupByToolkitOutput<ToolkitName>[] {+ return toolkits.map(toolkit => groupByToolkit(toolkit)(rest));+}diff --git a/ts/packages/cli/src/generation/python/generate-toolkit-sources.ts b/ts/packages/cli/src/generation/python/generate-toolkit-sources.tsnew file mode 100644index 000000000..1eddb1668--- /dev/null+++ b/ts/packages/cli/src/generation/python/generate-toolkit-sources.ts@@ -0,0 +1,80 @@+/**+ * @example+ *+ * ```python+ * class ABLY:+ * """Map of Composio's ABLY toolkit."""+ *+ * slug: str = "ably"+ *+ * class tools:+ * BATCH_PRESENCE = "ABLY_BATCH_PRESENCE"+ * BATCH_PRESENCE_HISTORY = "ABLY_BATCH_PRESENCE_HISTORY"+ * CREATE_CHANNEL = "ABLY_CREATE_CHANNEL"+ * DELETE_CHANNEL_SUBSCRIPTION = "ABLY_DELETE_CHANNEL_SUBSCRIPTION"+ *+ * class triggers:+ * pass+ * ```+ */++import { pipe, Record } from 'effect';+import type { ToolkitName } from 'src/models/toolkits';+import type { ToolkitIndex, ToolkitIndexData } from '../create-toolkit-index';++type SourceFile = [filename: string, content: string];++/**+ * Generates a list of Python source files that should be written to disk by the caller.+ */+export function generatePythonToolkitSources(index: ToolkitIndex): Array<SourceFile> {+ return pipe(index, Record.mapEntries(generatePythonToolkitSource), Record.toEntries);+}++function generatePythonToolkitSource(+ toolkit: ToolkitIndexData,+ toolkitName: ToolkitName+): SourceFile {+ const filename = `${toolkit.slug}.py`;++ const toolsEntries = (spacing: number) => {+ const spacePad = ' '.repeat(spacing);++ if (Record.size(toolkit.tools) > 0) {+ return Object.entries(toolkit.tools)+ .map(([toolName, toolValue]) => `${spacePad}${toolName} = "${toolValue}"`)+ .join('\n');+ }++ return `${spacePad}pass`;+ };++ const triggerTypesEntries = (spacing: number) => {+ const spacePad = ' '.repeat(spacing);++ if (Record.size(toolkit.triggerTypes) > 0) {+ return Object.entries(toolkit.triggerTypes)+ .map(([triggerName, triggerValue]) => `${spacePad}${triggerName} = "${triggerValue}"`)+ .join('\n');+ }++ return `${spacePad}pass`;+ };++ const filesource = `# Auto-generated by Composio CLI via \`composio py generate\`.+# Do not modify manually.++class ${toolkitName}:+ """Map of Composio's ${toolkitName} toolkit."""++ slug: str = "${toolkit.slug}"++ class tools:+${toolsEntries(8)}++ class triggers:+${triggerTypesEntries(8)}+`;++ return [filename, filesource];+}diff --git a/ts/packages/cli/src/generation/typescript/generate-index-source.ts b/ts/packages/cli/src/generation/typescript/generate-index-source.tsnew file mode 100644index 000000000..ab5190987--- /dev/null+++ b/ts/packages/cli/src/generation/typescript/generate-index-source.ts@@ -0,0 +1,142 @@+/**+ * @example+ *+ * ```typescript+ * // Map of Composio's ABLY toolkit.+ * export const ABLY = {+ * slug: "ably",+ * tools: {+ * BATCH_PRESENCE: "ABLY_BATCH_PRESENCE",+ * BATCH_PRESENCE_HISTORY: "ABLY_BATCH_PRESENCE_HISTORY",+ * CREATE_CHANNEL: "ABLY_CREATE_CHANNEL",+ * DELETE_CHANNEL_SUBSCRIPTION: "ABLY_DELETE_CHANNEL_SUBSCRIPTION",+ * GET_CHANNEL_DETAILS: "ABLY_GET_CHANNEL_DETAILS",+ * GET_CHANNEL_HISTORY: "ABLY_GET_CHANNEL_HISTORY",+ * GET_PRESENCE_HISTORY: "ABLY_GET_PRESENCE_HISTORY",+ * GET_SERVICE_TIME: "ABLY_GET_SERVICE_TIME",+ * GET_STATS: "ABLY_GET_STATS",+ * LIST_PUSH_CHANNEL_SUBSCRIPTIONS: "ABLY_LIST_PUSH_CHANNEL_SUBSCRIPTIONS",+ * PUBLISH_MESSAGE_TO_CHANNEL: "ABLY_PUBLISH_MESSAGE_TO_CHANNEL",+ * },+ * triggerTypes: {},+ * }+ * ```+ */++import * as ts from '@composio/ts-builders';+import { pipe, Record, Array as Arr } from 'effect';+import type { ToolkitIndex } from '../create-toolkit-index';++type generateTypeScriptIndexMapSourceParams = {+ banner: string;+ emitSingleFile: boolean;+};++export function generateIndexSource(params: generateTypeScriptIndexMapSourceParams) {+ return (index: ToolkitIndex) => {+ const indexMap = generateTypeScriptIndexMapSource(params)(index);+ const toolkitUnionType = generateToolkitUnionType(index);+ const toolsByToolkitType = generateToolsByToolkitType();++ const indexMapWithBanner = params.emitSingleFile+ ? indexMap+ : `${ts.stringify(ts.docComment(params.banner))}+${indexMap}`;++ // Add the Toolkit type to the generated code+ const code = `${indexMapWithBanner}+${ts.stringify(ts.docComment('Type declarations'))}+${toolkitUnionType}+${toolsByToolkitType}+`;++ return code;+ };+}++/**+ * Generates a list of Python source files that should be written to disk by the caller.+ */+export function generateTypeScriptIndexMapSource(params: generateTypeScriptIndexMapSourceParams) {+ return (index: ToolkitIndex): string => {+ const indexMapEntries = pipe(+ index,+ Record.map((_, key) => ts.propertyValue(key, ts.namedValue(key as string))),+ Record.toEntries,+ Arr.map(([_, value]) => value)+ );++ const indexMapFile = ts.file();++ for (const [toolkitName, value] of Record.toEntries(index)) {+ // Note: imports needd to be skipped when generating a single file+ if (params.emitSingleFile) {+ break;+ }++ indexMapFile.addImport(ts.moduleImport(`./${value.slug}.ts`).named(toolkitName));+ }++ indexMapFile.add(+ ts+ .moduleExport(+ ts.constDeclaration('composio').setValue(ts.objectValue().addMultiple(indexMapEntries))+ )+ .setDocComment(ts.docComment('Map of Composio toolkits to actions.'))+ );++ const indexMapFileSource = ts.stringify(indexMapFile);++ return indexMapFileSource;+ };+}++export function generateToolkitUnionType(index: ToolkitIndex): string {+ const toolkitModules = pipe(+ index,+ Record.toEntries,+ Arr.map(([key, _]) => key)+ );++ const file = ts.file();+ const doc = ts.docComment('Union of all available toolkits.');++ file.add(+ ts+ .moduleExport(+ ts.typeDeclaration(+ 'Toolkit',+ toolkitModules.length === 0+ ? ts.neverType+ : ts.unionType(toolkitModules.map(slug => ts.stringLiteral(slug))).formatMultiline()+ )+ )+ .setDocComment(doc)+ );++ return ts.stringify(file);+}++export function generateToolsByToolkitType(): string {+ const file = ts.file();+ const doc = ts.docComment('Given a toolkit, returns the tools available for that toolkit.');++ file.add(+ ts+ .moduleExport(+ ts+ .typeDeclaration(+ 'ToolsByToolkit',+ ts.typeOfType(ts.keyType(ts.namedType('composio'), ts.namedType('Toolkit')))+ )+ .addGenericParameter(+ ts+ .genericParameter('Toolkit')+ .extends(ts.keyOfType(ts.typeOfType(ts.namedType('composio'))))+ )+ )+ .setDocComment(doc)+ );++ return ts.stringify(file);+}diff --git a/ts/packages/cli/src/generation/typescript/generate-toolkit-sources.ts b/ts/packages/cli/src/generation/typescript/generate-toolkit-sources.tsnew file mode 100644index 000000000..81810979d--- /dev/null+++ b/ts/packages/cli/src/generation/typescript/generate-toolkit-sources.ts@@ -0,0 +1,104 @@+/**+ * @example+ *+ * ```typescript+ * // Map of Composio's ABLY toolkit.+ * export const ABLY = {+ * slug: "ably",+ * tools: {+ * BATCH_PRESENCE: "ABLY_BATCH_PRESENCE",+ * BATCH_PRESENCE_HISTORY: "ABLY_BATCH_PRESENCE_HISTORY",+ * CREATE_CHANNEL: "ABLY_CREATE_CHANNEL",+ * DELETE_CHANNEL_SUBSCRIPTION: "ABLY_DELETE_CHANNEL_SUBSCRIPTION",+ * GET_CHANNEL_DETAILS: "ABLY_GET_CHANNEL_DETAILS",+ * GET_CHANNEL_HISTORY: "ABLY_GET_CHANNEL_HISTORY",+ * GET_PRESENCE_HISTORY: "ABLY_GET_PRESENCE_HISTORY",+ * GET_SERVICE_TIME: "ABLY_GET_SERVICE_TIME",+ * GET_STATS: "ABLY_GET_STATS",+ * LIST_PUSH_CHANNEL_SUBSCRIPTIONS: "ABLY_LIST_PUSH_CHANNEL_SUBSCRIPTIONS",+ * PUBLISH_MESSAGE_TO_CHANNEL: "ABLY_PUBLISH_MESSAGE_TO_CHANNEL",+ * },+ * triggerTypes: {},+ * }+ * ```+ */++import * as ts from '@composio/ts-builders';+import { pipe, Record } from 'effect';+import type { ToolkitName } from 'src/models/toolkits';+import type { ToolkitIndex, ToolkitIndexData } from '../create-toolkit-index';++type SourceFile = [filename: string, content: string];++type GenerateTypeScriptToolkitSourcesInput = {+ banner: string;+ emitSingleFile: boolean;+ outputDir: string;+};++/**+ * Generates a list of Python source files that should be written to disk by the caller.+ */+export function generateTypeScriptToolkitSources(params: GenerateTypeScriptToolkitSourcesInput) {+ return (index: ToolkitIndex): Array<SourceFile> => {+ const toolkitSources = pipe(+ index,+ Record.mapEntries(generateTypeScriptToolkitSource(params)),+ Record.toEntries+ );++ return toolkitSources;+ };+}++function generateTypeScriptToolkitSource(_params: GenerateTypeScriptToolkitSourcesInput) {+ return (+ { slug, tools, triggerTypes }: ToolkitIndexData,+ toolkitName: ToolkitName+ ): SourceFile => {+ const filename = `${slug}.ts`;++ const file = ts.file();++ const entry = ts.propertyValue(+ toolkitName,+ ts+ .objectValue()+ .add(ts.propertyValue('slug', ts.stringLiteral(slug).asValue()))+ .add(+ ts.propertyValue(+ 'tools',+ ts+ .objectValue()+ .addMultiple(+ Object.entries(tools).map(([toolName, tool]) =>+ ts.propertyValue(toolName, ts.stringLiteral(tool).asValue())+ )+ )+ )+ )+ .add(+ ts.propertyValue(+ 'triggerTypes',+ ts+ .objectValue()+ .addMultiple(+ Object.entries(triggerTypes).map(([triggerTypeSlug, triggerType]) =>+ ts.propertyValue(triggerTypeSlug, ts.stringLiteral(triggerType).asValue())+ )+ )+ )+ )+ );++ file.add(+ ts+ .moduleExport(ts.constDeclaration(entry.name as string).setValue(entry.value))+ .setDocComment(ts.docComment(`Map of Composio's ${entry.name} toolkit.`))+ );++ const filesource = ts.stringify(file);++ return [filename, filesource];+ };+}diff --git a/ts/packages/cli/src/generation/typescript/generate.ts b/ts/packages/cli/src/generation/typescript/generate.tsnew file mode 100644index 000000000..266fa1103--- /dev/null+++ b/ts/packages/cli/src/generation/typescript/generate.ts@@ -0,0 +1,37 @@+import * as ts from '@composio/ts-builders';+import path from 'node:path';+import type { ToolkitIndex } from 'src/generation/create-toolkit-index';+import { generateTypeScriptToolkitSources } from './generate-toolkit-sources';+import { generateIndexSource } from './generate-index-source';++type GenerateTypeScriptSourcesParams = {+ banner: string;+ emitSingleFile: boolean;+ outputDir: string;+};++export function generateTypeScriptSources(params: GenerateTypeScriptSourcesParams) {+ return (index: ToolkitIndex): Array<readonly [string, string]> => {+ const toolkiteSources = generateTypeScriptToolkitSources(params)(index);++ const indexSource = generateIndexSource(params)(index);+ const indexFilename = path.join(params.outputDir, 'index.ts');++ if (!params.emitSingleFile) {+ return [+ ...toolkiteSources.map(+ ([filename, content]) => [path.join(params.outputDir, filename), content] as const+ ),+ [indexFilename, indexSource] as const,+ ] as const;+ }++ const localToolkitsSources = toolkiteSources.map(([_, content]) => content).join('\n');++ const indexSourceSingleFile = `${ts.stringify(ts.docComment(params.banner))}+${localToolkitsSources}+${indexSource}+`;+ return [[indexFilename, indexSourceSingleFile] as const];+ };+}diff --git a/ts/packages/cli/src/models/session.ts b/ts/packages/cli/src/models/session.tsnew file mode 100644index 000000000..d624717a2--- /dev/null+++ b/ts/packages/cli/src/models/session.ts@@ -0,0 +1,51 @@+import { Schema } from 'effect';+import { JSONTransformSchema } from './utils/json-transform-schema';++export const Session = Schema.Struct({+ id: Schema.String,+ code: Schema.String,+ expiresAt: Schema.DateTimeUtc,+ status: Schema.Literal('pending', 'linked'),+}).annotations({ identifier: 'Session' });+export type Session = Schema.Schema.Type<typeof Session>;++export const SessionJSON = JSONTransformSchema(Session);+export const sessionFromJSON = Schema.decode(SessionJSON);+export const sessionToJSON = Schema.encode(SessionJSON);++const SessionAccount = Schema.Struct({+ id: Schema.String,+ email: Schema.String,+ name: Schema.String,+}).annotations({ identifier: 'SessionAccount' });+export type SessionAccount = Schema.Schema.Type<typeof SessionAccount>;++export const LinkedSession = Session.omit('status')+ .pipe(+ Schema.extend(+ Schema.Struct({+ status: Schema.Literal('linked'),+ account: SessionAccount.annotations({ identifier: 'LinkedSession.Account' }),+ })+ )+ )+ .annotations({ identifier: 'LinkedSession' });+export type LinkedSession = Schema.Schema.Type<typeof LinkedSession>;++export const LinkedSessionJSON = JSONTransformSchema(LinkedSession);+export const LinkedSessionFromJSON = Schema.decode(LinkedSessionJSON);+export const LinkedSessionToJSON = Schema.encode(LinkedSessionJSON);++export const RetrievedSession = Schema.Union(+ Schema.Struct({ ...Session.fields, status: Schema.Literal('pending') }),+ Schema.Struct({+ ...Session.fields,+ account: SessionAccount.annotations({ identifier: 'RetrievedSession.Account' }),+ status: Schema.Literal('linked'),+ })+).annotations({ identifier: 'RetrievedSession' });+export type RetrievedSession = Schema.Schema.Type<typeof RetrievedSession>;++export const RetrievedSessionJSON = JSONTransformSchema(RetrievedSession);+export const retrievedSessionFromJSON = Schema.decode(RetrievedSessionJSON);+export const retrievedSessionToJSON = Schema.encode(RetrievedSessionJSON);diff --git a/ts/packages/cli/src/models/toolkits.ts b/ts/packages/cli/src/models/toolkits.tsnew file mode 100644index 000000000..cb656d666--- /dev/null+++ b/ts/packages/cli/src/models/toolkits.ts@@ -0,0 +1,28 @@+import { Brand, Schema } from 'effect';+import { JSONTransformSchema } from './utils/json-transform-schema';++export const Toolkit = Schema.Struct({+ name: Schema.String, // "Gmail"+ slug: Schema.String, // "gmail"+ auth_schemes: Schema.Array(Schema.String), // [ "OAUTH2", "BEARER_TOKEN" ]+ composio_managed_auth_schemes: Schema.Array(Schema.String), // [ "OAUTH2" ]+ is_local_toolkit: Schema.Boolean,+ meta: Schema.Struct({+ description: Schema.String,+ categories: Schema.Array(Schema.Unknown),+ created_at: Schema.DateTimeUtc, // "2024-05-03T11:44:32.061Z"+ updated_at: Schema.DateTimeUtc, // "2024-05-03T11:44:32.061Z"+ }),+ no_auth: Schema.Boolean,+}).annotations({ identifier: 'Toolkit' });+export type Toolkit = Schema.Schema.Type<typeof Toolkit>;++export const Toolkits = Schema.Array(Toolkit);+export type Toolkits = Schema.Schema.Type<typeof Toolkits>;++export const ToolkitsJSON = JSONTransformSchema(Toolkits);+export const toolkitsFromJSON = Schema.decode(ToolkitsJSON);+export const toolkitsToJSON = Schema.encode(ToolkitsJSON);++export type ToolkitName = string & Brand.Brand<'ToolkitName'>;+export const ToolkitName = Brand.nominal<ToolkitName>();diff --git a/ts/packages/cli/src/models/tools.ts b/ts/packages/cli/src/models/tools.tsnew file mode 100644index 000000000..d3fa3dac8--- /dev/null+++ b/ts/packages/cli/src/models/tools.ts@@ -0,0 +1,20 @@+import { Brand, Schema } from 'effect';+import { JSONTransformSchema } from './utils/json-transform-schema';++export const Tool = Schema.String;+export type Tool = Schema.Schema.Type<typeof Tool>;++export const Tools = Schema.Array(Tool);+export type Tools = Schema.Schema.Type<typeof Tools>;++export const ToolsJSON = JSONTransformSchema(Tools);+export const toolsFromJSON = Schema.decode(ToolsJSON);+export const toolsToJSON = Schema.encode(ToolsJSON);++// E.g., `SEND_EMAIL`+export type ToolName = string & Brand.Brand<'ToolName'>;+export const ToolName = Brand.nominal<ToolName>();++// E.g., `GMAIL_SEND_EMAIL`+export type ToolNameWithToolkitPrefix = string & Brand.Brand<'ToolNameWithToolkitPrefix'>;+export const ToolNameWithToolkitPrefix = Brand.nominal<ToolNameWithToolkitPrefix>();diff --git a/ts/packages/cli/src/models/trigger-types.ts b/ts/packages/cli/src/models/trigger-types.tsnew file mode 100644index 000000000..ed15a5028--- /dev/null+++ b/ts/packages/cli/src/models/trigger-types.ts@@ -0,0 +1,21 @@+import { Brand, Schema } from 'effect';+import { JSONTransformSchema } from './utils/json-transform-schema';++export const TriggerType = Schema.String;+export type TriggerType = Schema.Schema.Type<typeof TriggerType>;++export const TriggerTypes = Schema.Array(TriggerType);+export type TriggerTypes = Schema.Schema.Type<typeof TriggerTypes>;++export const TriggerTypesJSON = JSONTransformSchema(TriggerTypes);+export const triggerTypesFromJSON = Schema.decode(TriggerTypesJSON);+export const triggerTypesToJSON = Schema.encode(TriggerTypesJSON);++// E.g., `NEW_EMAIL`+export type TriggerTypeName = string & Brand.Brand<'TriggerTypeName'>;+export const TriggerTypeName = Brand.nominal<TriggerTypeName>();++// E.g., `GMAIL_NEW_EMAIL`+export type TriggerTypeNameWithToolkitPrefix = string &+ Brand.Brand<'TriggerTypeNameWithToolkitPrefix'>;+export const TriggerTypeNameWithToolkitPrefix = Brand.nominal<TriggerTypeNameWithToolkitPrefix>();diff --git a/ts/packages/cli/src/models/utils/json-transform-schema.ts b/ts/packages/cli/src/models/utils/json-transform-schema.tsnew file mode 100644index 000000000..e3377bf0b--- /dev/null+++ b/ts/packages/cli/src/models/utils/json-transform-schema.ts@@ -0,0 +1,18 @@+import { Schema, ParseResult } from 'effect';+import superjson from 'superjson';++export function JSONTransformSchema<To extends Schema.Schema.Any>(to: To) {+ return Schema.transformOrFail(Schema.String, to, {+ strict: true,+ encode: (obj, _options, ast) =>+ ParseResult.try({+ try: () => superjson.stringify(obj),+ catch: e => new ParseResult.Type(ast, obj, (e as Error).message),+ }),+ decode: (str, _options, ast) =>+ ParseResult.try({+ try: () => superjson.parse(str),+ catch: e => new ParseResult.Type(ast, str, (e as Error).message),+ }),+ });+}diff --git a/ts/packages/cli/src/services/composio-clients.ts b/ts/packages/cli/src/services/composio-clients.tsnew file mode 100644index 000000000..170977065--- /dev/null+++ b/ts/packages/cli/src/services/composio-clients.ts@@ -0,0 +1,191 @@+import { pipe, Data, Effect, Option, Schema, Array, Order } from 'effect';+import { APP_CONFIG } from 'src/effects/app-config';+import { Composio as _RawComposioClient } from '@composio/client';+import { Toolkit, Toolkits } from 'src/models/toolkits';+import { Tools } from 'src/models/tools';+import { LinkedSession, Session, RetrievedSession } from 'src/models/session';+import { TriggerType } from 'src/models/trigger-types';++/**+ * Error types+ */++/**+ * Error thrown when a HTTP request fails.+ */+export class HttpServerError extends Data.TaggedError('services/HttpServerError')<{+ readonly cause: Error;+ readonly message: string;+}> {}++/**+ * Error thrown when a HTTP response doesn't match the expected response schema.+ */+export class HttpDecodingError extends Data.TaggedError('services/HttpDecodingError')<{+ readonly cause: Error;+ readonly message: string;+}> {}++export type HttpError = HttpServerError | HttpDecodingError;++/**+ * Response schemas+ */++export const CliCreateSessionResponse = Session;+export type CliCreateSessionResponse = Schema.Schema.Type<typeof CliCreateSessionResponse>;++export const CliLinkSessionResponse = LinkedSession;+export type CliLinkSessionResponse = Schema.Schema.Type<typeof CliLinkSessionResponse>;++export const CliRetrieveSessionResponse = RetrievedSession;+export type CliRetrieveSessionResponse = Schema.Schema.Type<typeof CliRetrieveSessionResponse>;++export const ToolkitsResponse = Schema.Struct({+ items: Toolkits,+ total_pages: Schema.Int,+ next_cursor: Schema.NullOr(Schema.Int),+}).annotations({ identifier: 'ToolkitsResponse' });+export type ToolkitsResponse = Schema.Schema.Type<typeof ToolkitsResponse>;++export const ToolsResponse = Tools;+export type ToolsResponse = Schema.Schema.Type<typeof ToolsResponse>;++export const TriggerTypesResponse = Schema.Array(TriggerType);+export type TriggerResponse = Schema.Schema.Type<typeof TriggerTypesResponse>;++/**+ * Utilities+ */++// Utility function for calling the Composio API and decoding its response.+// eslint-disable-next-line @typescript-eslint/no-explicit-any+const callClient = <T, S extends Schema.Schema<any, any>>(+ apiCall: () => Promise<T>,+ responseSchema: S+): Effect.Effect<Schema.Schema.Type<S>, HttpError> =>+ pipe(+ Effect.tryPromise({+ try: apiCall,+ catch: error => {+ const e = error as Error;+ return new HttpServerError({+ cause: e,+ message: e.message,+ });+ },+ }),+ Effect.flatMap(json => Schema.decodeUnknown(responseSchema)(json)),+ Effect.catchTag('ParseError', e => {+ return new HttpDecodingError({+ cause: e,+ message: e.message,+ });+ })+ );++/**+ * Services+ */++// Service that wraps the raw Composio client, which is shared by all client services.+class ComposioClientLive extends Effect.Service<ComposioClientLive>()(+ 'services/ComposioClientLive',+ {+ effect: Effect.gen(function* () {+ const apiKey = yield* APP_CONFIG['API_KEY'];+ const baseURLOpt = yield* APP_CONFIG['BASE_URL'];+ const baseURL = Option.getOrUndefined(baseURLOpt);++ yield* Effect.logDebug('Creating raw Composio client...');+ const client = new _RawComposioClient({ apiKey, baseURL });++ return {+ toolkits: {+ /**+ * Retrieves a comprehensive list of toolkits that are available to the authenticated project.+ */+ list: () => callClient(() => client.toolkits.list(), ToolkitsResponse),+ },+ tools: {+ /**+ * Retrieve a list of all available tool enumeration values (tool slugs) for the project.+ */+ retrieveEnum: () => callClient(() => client.tools.retrieveEnum(), ToolsResponse),+ },+ triggersTypes: {+ /**+ * Retrieves a list of all available trigger type enum values that can be used across the API.+ */+ retrieveEnum: () =>+ callClient(() => client.triggersTypes.retrieveEnum(), TriggerTypesResponse),+ },+ v3: {+ cli: {+ /**+ * Generates a new CLI session with a random 6-character code.+ */+ createSession: () =>+ callClient(() => client.v3.cli.createSession(), CliCreateSessionResponse),++ /**+ * Retrieves the current state of a CLI session using either the session ID (UUID) or the 6-character code.+ */+ retrieveSession: (session: { id: string }) =>+ callClient(() => client.v3.cli.retrieveSession(session), CliRetrieveSessionResponse),++ /**+ * Links a pending CLI session to the currently authenticated user.+ */+ linkSession: (session: { id: string }) =>+ callClient(() => client.v3.cli.linkSession(session), CliLinkSessionResponse),+ },+ },+ };+ }),+ dependencies: [],+ }+) {}++export class ComposioToolkitsRepository extends Effect.Service<ComposioToolkitsRepository>()(+ 'services/ComposioToolkitsRepository',+ {+ effect: Effect.gen(function* () {+ const client = yield* ComposioClientLive;++ return {+ getToolkits: () =>+ client.toolkits.list().pipe(+ Effect.map(response => response.items),+ Effect.flatMap(toolkits =>+ Effect.gen(function* () {+ // Sort apps by slug+ const orderBySlug = Order.mapInput(Order.string, (app: Toolkit) => app.slug);+ return Array.sort(toolkits, orderBySlug);+ })+ )+ ),+ getTools: () => client.tools.retrieveEnum(),+ getTriggerTypes: () => client.triggersTypes.retrieveEnum(),+ };+ }),+ dependencies: [ComposioClientLive.Default],+ }+) {}++export class ComposioSessionRepository extends Effect.Service<ComposioSessionRepository>()(+ 'services/ComposioSessionRepository',+ {+ effect: Effect.gen(function* () {+ const client = yield* ComposioClientLive;++ return {+ createSession: () => client.v3.cli.createSession(),+ retrieveSession: (session: { id: string }) =>+ client.v3.cli.retrieveSession({ id: session.id }),+ linkSession: (session: { id: string }) => client.v3.cli.linkSession({ id: session.id }),+ };+ }),+ dependencies: [ComposioClientLive.Default],+ }+) {}diff --git a/ts/packages/cli/src/services/env-lang-detector.ts b/ts/packages/cli/src/services/env-lang-detector.tsnew file mode 100644index 000000000..9b6879218--- /dev/null+++ b/ts/packages/cli/src/services/env-lang-detector.ts@@ -0,0 +1,219 @@+import { BunFileSystem } from '@effect/platform-bun';+import { pipe, Data, Effect } from 'effect';+import { FileSystem } from '@effect/platform';++export class EnvLangDetectorError extends Data.TaggedError('services/DetectEnvLangError')<{+ readonly cause: Error;+ readonly message: string;+}> {}++// Service that attempts to detect the language of the project in the current working directory.+export class EnvLangDetector extends Effect.Service<EnvLangDetector>()('services/EnvLangDetector', {+ effect: Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;++ return {+ detectEnvLanguage: (cwd: string) =>+ Effect.gen(function* () {+ const files = yield* pipe(+ fs.readDirectory(cwd),+ Effect.catchAll(e =>+ Effect.fail(+ new EnvLangDetectorError({ cause: e, message: `Failed to read directory ${cwd}` })+ )+ )+ );++ // Convert to lowercase for case-insensitive comparison+ const fileNames = files.map(f => f.toLowerCase());+ yield* Effect.logDebug(`Files in directory ${cwd}:\n${fileNames.join('\n')}`);++ // TypeScript project indicators (in order of precedence)+ const typescriptIndicators = [+ 'tsconfig.json',+ 'package.json',+ 'yarn.lock',+ 'package-lock.json',+ 'pnpm-lock.yaml',+ 'bun.lockb',+ 'deno.json',+ 'deno.jsonc',+ ];++ // Python project indicators (in order of precedence)+ const pythonIndicators = [+ 'pyproject.toml',+ 'setup.py',+ 'requirements.txt',+ 'pipfile',+ 'pipfile.lock',+ 'poetry.lock',+ 'conda.yaml',+ 'environment.yml',+ 'setup.cfg',+ 'tox.ini',+ 'pytest.ini',+ '__pycache__',+ ];++ // Check for TypeScript indicators first+ const hasTypescriptIndicator = typescriptIndicators.some(indicator =>+ fileNames.includes(indicator)+ );++ // Check for Python indicators+ const hasPythonIndicator = pythonIndicators.some(indicator =>+ fileNames.includes(indicator)+ );++ yield* Effect.logDebug(`TypeScript indicators found: ${hasTypescriptIndicator}`);+ yield* Effect.logDebug(`Python indicators found: ${hasPythonIndicator}`);++ // Additional checks for file extensions if no clear indicators found+ if (!hasTypescriptIndicator && !hasPythonIndicator) {+ // Get actual file names (not lowercase) for extension checking+ const hasTypeScriptFiles = files.some(+ file =>+ file.endsWith('.ts') ||+ file.endsWith('.tsx') ||+ file.endsWith('.mts') ||+ file.endsWith('.cts')+ );++ const hasPythonFiles = files.some(+ file =>+ file.endsWith('.py') ||+ file.endsWith('.pyw') ||+ file.endsWith('.pyi') ||+ file.endsWith('.pyx')+ );++ if (hasTypeScriptFiles && !hasPythonFiles) {+ return 'TypeScript' as const;+ }++ if (hasPythonFiles && !hasTypeScriptFiles) {+ return 'Python' as const;+ }++ // If both or neither are found, check for more files by reading subdirectories+ // This is a more exhaustive check+ const allFiles: string[] = [];++ // Don't recurse into common directories that might contain false positives+ const skipDirs = [+ '.composio',+ 'node_modules',+ '.git',+ '__pycache__',+ '.venv',+ 'venv',+ 'env',+ 'dist',+ 'build',+ ];++ // Recursively collect files from immediate subdirectories+ yield* Effect.logInfo('Checking subdirectories for more files...');++ for (const item of files) {+ const itemPath = `${cwd}/${item}`;+ const stat = yield* pipe(+ fs.stat(cwd),+ Effect.catchAll(e =>+ Effect.fail(+ new EnvLangDetectorError({+ cause: e,+ message: `Failed to read file ${itemPath}`,+ })+ )+ )+ );++ if (stat.type === 'Directory') {+ if (!skipDirs.includes(item.toLowerCase())) {+ const subFiles = yield* pipe(+ fs.readDirectory(item),+ Effect.catchAll(e =>+ Effect.fail(+ new EnvLangDetectorError({+ cause: e,+ message: `Failed to read directory ${item}`,+ })+ )+ )+ );+ allFiles.push(...subFiles);+ }+ }+ }++ const allFileNames = [...files, ...allFiles];++ const deepTsFiles = allFileNames.filter(+ file =>+ file.endsWith('.ts') ||+ file.endsWith('.tsx') ||+ file.endsWith('.mts') ||+ file.endsWith('.cts')+ ).length;++ const deepPyFiles = allFileNames.filter(+ file =>+ file.endsWith('.py') ||+ file.endsWith('.pyw') ||+ file.endsWith('.pyi') ||+ file.endsWith('.pyx')+ ).length;++ // Decide based on which has more files+ if (deepTsFiles > deepPyFiles && deepTsFiles > 0) {+ return 'TypeScript' as const;+ }++ if (deepPyFiles > deepTsFiles && deepPyFiles > 0) {+ return 'Python' as const;+ }+ }++ // Prioritize based on strength of indicators+ if (hasTypescriptIndicator && hasPythonIndicator) {+ // Both present - prioritize based on most definitive files+ const strongTsIndicators = ['tsconfig.json', 'package.json'];+ const strongPyIndicators = ['pyproject.toml', 'setup.py'];++ const hasStrongTs = strongTsIndicators.some(indicator => fileNames.includes(indicator));+ const hasStrongPy = strongPyIndicators.some(indicator => fileNames.includes(indicator));++ if (hasStrongTs && !hasStrongPy) {+ return 'TypeScript' as const;+ }+ if (hasStrongPy && !hasStrongTs) {+ return 'Python' as const;+ }++ // If both have strong indicators, default to TypeScript+ // (this is arbitrary but package.json is very common)+ return 'TypeScript' as const;+ }++ if (hasTypescriptIndicator) {+ return 'TypeScript' as const;+ }++ if (hasPythonIndicator) {+ return 'Python' as const;+ }++ // No clear indicators found+ return yield* Effect.fail(+ new EnvLangDetectorError({+ cause: new Error('Unable to detect project language'),+ message: `Could not determine if directory '${cwd}' contains a Python or TypeScript project. No recognizable project files or patterns found.`,+ })+ );+ }),+ };+ }),+ dependencies: [BunFileSystem.layer],+}) {}diff --git a/ts/packages/cli/src/services/node-process.ts b/ts/packages/cli/src/services/node-process.tsnew file mode 100644index 000000000..d36c2725b--- /dev/null+++ b/ts/packages/cli/src/services/node-process.ts@@ -0,0 +1,12 @@+import process from 'node:process';+import { Effect } from 'effect';++// Service to that wraps `node:process`, for testing purposes.+export class NodeProcess extends Effect.Service<NodeProcess>()('services/NodeProcess', {+ sync: () => ({+ cwd: process.cwd(),+ platform: process.platform,+ arch: process.arch,+ }),+ dependencies: [],+}) {}diff --git a/ts/packages/cli/src/services/user-config.ts b/ts/packages/cli/src/services/user-config.tsnew file mode 100644index 000000000..c5d8d1a4e--- /dev/null+++ b/ts/packages/cli/src/services/user-config.ts@@ -0,0 +1,95 @@+import path from 'node:path';+import { Option, Effect, ConfigProvider, Layer, Logger } from 'effect';+import * as constants from 'src/constants';+import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';+import { configProviderFromLazyJson } from 'src/effects/from-lazy-json';+import { APP_CONFIG } from 'src/effects/app-config';+import { setupCacheDir } from 'src/effects/setup-cache-dir';++/**+ * Define where `effect/Config` reads config values from.+ * Lookup priority:+ * 1. Environment variables+ * 2. JSON user file (lazily loaded only when absolutely needed)+ *+ * Environment variables' keys are in upper snake case.+ * They are prefixed with `COMPOSIO_`, with the only exception of `DEBUG_*` variables.+ * The prefix is stripped when reading the environment variables from `effect/Config`.+ *+ * @example+ * ```sh+ * # Environment variable+ * COMPOSIO_API_KEY=your_api_key+ * ```+ *+ * ```jsonc+ * // JSON User config file+ * {+ * "api_key": "your_api_key"+ * }+ * ```+ *+ * Read via `yield* Config.string('API_KEY')`.+ */+const ConfigProviderLive = Effect.gen(function* () {+ // TODO: fix this to avoid `API_KEY` errors when using commands that don't need it.+ const cacheDir = yield* setupCacheDir;+ const jsonUserConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);+ const configProviderFromUserFile = yield* configProviderFromLazyJson(jsonUserConfigPath);+ // const configProviderFromUserFile = yield* configProviderFromLazyJson('/tmp');++ // start by reading from env vars+ const configProvider = ConfigProvider.fromEnv()+ // prefix env var keys+ .pipe(+ ConfigProvider.mapInputPath(key => {+ if (key.startsWith('DEBUG_OVERRIDE_') || key.startsWith('FORCE_')) {+ return key;+ }++ return `${constants.APP_ENV_CONFIG_KEY_PREFIX}${key}`;+ })+ )+ // fall back to user config file, which is lazily loaded+ .pipe(+ ConfigProvider.orElse(() => {+ // e.g., read `json['api_key']` as `Config.string('COMPOSIO_API_KEY')`+ return configProviderFromUserFile.pipe(ConfigProvider.snakeCase);+ })+ );++ return Layer.setConfigProvider(configProvider);+}).pipe(Layer.unwrapEffect);++/**+ * Tentatively set the minimum log level if found in the config.+ */+const LoggerFromConfigLive = Effect.map(+ APP_CONFIG['LOG_LEVEL'],+ Option.match({+ onNone: () => Layer.empty,+ onSome: logLevel => Logger.minimumLogLevel(logLevel),+ })+).pipe(Layer.unwrapEffect);++/**+ * Print a debug message for each debug environment variable that overrides dynamic configuration values.+ */+const logDebugOverride = Effect.gen(function* () {+ const debugOverrideEntries = Object.keys(DEBUG_OVERRIDE_CONFIG) as [+ keyof typeof DEBUG_OVERRIDE_CONFIG,+ ];++ for (const key of debugOverrideEntries) {+ const configEntry = yield* DEBUG_OVERRIDE_CONFIG[key];+ if (Option.isSome(configEntry)) {+ yield* Effect.logDebug(+ `Using \`${constants.DEBUG_OVERRIDE_ENV_CONFIG_KEY_PREFIX}${key}\` debug override`+ );+ }+ }+});++export const UserConfigLive = Layer.provide(LoggerFromConfigLive, ConfigProviderLive).pipe(+ Layer.tap(() => logDebugOverride)+);diff --git a/ts/packages/cli/src/type-utils.ts b/ts/packages/cli/src/type-utils.tsnew file mode 100644index 000000000..5edb64adf--- /dev/null+++ b/ts/packages/cli/src/type-utils.ts@@ -0,0 +1,4 @@+import type { Command } from '@effect/cli';++export type GetCmdParams<T> =+ T extends Command.Command<infer _Name extends string, unknown, unknown, infer P> ? P : never;diff --git a/ts/packages/cli/test/__fixtures__/python-project/requirements.txt b/ts/packages/cli/test/__fixtures__/python-project/requirements.txtnew file mode 100644index 000000000..72fd40605--- /dev/null+++ b/ts/packages/cli/test/__fixtures__/python-project/requirements.txt@@ -0,0 +1 @@+click=8.1.2diff --git a/ts/packages/cli/test/__fixtures__/python-project/setup.py b/ts/packages/cli/test/__fixtures__/python-project/setup.pynew file mode 100644index 000000000..e69de29bbdiff --git a/ts/packages/cli/test/__fixtures__/typescript-project/package.json b/ts/packages/cli/test/__fixtures__/typescript-project/package.jsonnew file mode 100644index 000000000..97f8ad70e--- /dev/null+++ b/ts/packages/cli/test/__fixtures__/typescript-project/package.json@@ -0,0 +1,5 @@+{+ "devDependencies": {+ "typescript": "^5.8.3"+ }+}diff --git a/ts/packages/cli/test/__fixtures__/typescript-project/tsconfig.json b/ts/packages/cli/test/__fixtures__/typescript-project/tsconfig.jsonnew file mode 100644index 000000000..840cb4edd--- /dev/null+++ b/ts/packages/cli/test/__fixtures__/typescript-project/tsconfig.json@@ -0,0 +1,20 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "paths": {+ "src/*": ["./src/*"],+ "test/*": ["./test/*"]+ },+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true+ },+ "include": ["src"],+ "exclude": ["**/dist", "**/node_modules", "test/__fixtures__/**"]+}diff --git a/ts/packages/cli/test/__utils__/cli.ts b/ts/packages/cli/test/__utils__/cli.tsnew file mode 100644index 000000000..a66d0a289--- /dev/null+++ b/ts/packages/cli/test/__utils__/cli.ts@@ -0,0 +1,10 @@+import { Effect } from 'effect';+import * as Cli from 'src/commands';++// Run CLI in test environment+export const cli = (args: ReadonlyArray<string>) =>+ Effect.flatMap(Cli.runWithConfig, run => run(['node', '<CMD>', ...args])) satisfies Effect.Effect<+ void,+ any,+ any+ >;diff --git a/ts/packages/cli/test/__utils__/index.ts b/ts/packages/cli/test/__utils__/index.tsnew file mode 100644index 000000000..a8dbae05b--- /dev/null+++ b/ts/packages/cli/test/__utils__/index.ts@@ -0,0 +1,7 @@+import pkg from '../../package.json' with { type: 'json' };++export * as MockConsole from './services/mock-console';+export * as MockTerminal from './services/mock-terminal';+export { TestLayer as TestLive, runEffect } from './services/test-layer';+export { cli } from './cli';+export { pkg };diff --git a/ts/packages/cli/test/__utils__/models/toolkits.ts b/ts/packages/cli/test/__utils__/models/toolkits.tsnew file mode 100644index 000000000..bfee182fc--- /dev/null+++ b/ts/packages/cli/test/__utils__/models/toolkits.ts@@ -0,0 +1,17 @@+import { Arbitrary, FastCheck } from 'effect';+import { Toolkit } from 'src/models/toolkits';++const ToolkitArbitary = Arbitrary.make(Toolkit);++/**+ * Creates test toolkit instances by merging arbitrary generated toolkit data with provided subset values.+ * Useful for generating test data that maintains consistent identifiers while having realistic randomized properties.+ */+export function makeTestToolkits(inputs: Array<Pick<Toolkit, 'name' | 'slug'>>) {+ const samples = FastCheck.sample(ToolkitArbitary, {+ numRuns: inputs.length,+ });++ const testToolkits = samples.map((sample, i) => ({ ...sample, ...inputs[i] }));+ return testToolkits;+}diff --git a/ts/packages/cli/test/__utils__/sanitize.ts b/ts/packages/cli/test/__utils__/sanitize.tsnew file mode 100644index 000000000..09b316768--- /dev/null+++ b/ts/packages/cli/test/__utils__/sanitize.ts@@ -0,0 +1,9 @@+import { pipe, Effect, String } from 'effect';+import { getVersion } from 'src/effects/version';++export const sanitize = (str: string) =>+ Effect.gen(function* () {+ const version = yield* getVersion;++ return pipe(str, String.replaceAll(version, '<VERSION>'));+ });diff --git a/ts/packages/cli/test/__utils__/services/mock-console.ts b/ts/packages/cli/test/__utils__/services/mock-console.tsnew file mode 100644index 000000000..dc980ed0d--- /dev/null+++ b/ts/packages/cli/test/__utils__/services/mock-console.ts@@ -0,0 +1,82 @@+// Inspired from https://github.com/Effect-TS/effect/blob/a2d57c9ac596445009ca12859b78e00e5d89b936/packages/cli/test/services/MockConsole.ts.++import * as Array from 'effect/Array';+import * as Console from 'effect/Console';+import * as Context from 'effect/Context';+import * as Effect from 'effect/Effect';+import * as Ref from 'effect/Ref';++export interface MockConsole extends Console.Console {+ readonly getLines: (+ params?: Partial<{+ readonly stripAnsi: boolean;+ }>+ ) => Effect.Effect<ReadonlyArray<string>>;+}++export const MockConsole = Context.GenericTag<Console.Console, MockConsole>('effect/Console');+const pattern = new RegExp(+ [+ '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',+ '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))',+ ].join('|'),+ 'g'+);++const stripAnsi = (str: string) => str.replace(pattern, '');++export const make = Effect.gen(function* () {+ const lines = yield* Ref.make(Array.empty<string>());++ const getLines: MockConsole['getLines'] = (params = {}) =>+ Ref.get(lines).pipe(+ Effect.map(lines => (params.stripAnsi || false ? Array.map(lines, stripAnsi) : lines))+ );++ const log: MockConsole['log'] = (...args) => {+ return Ref.update(lines, Array.appendAll(args));+ };++ const info: MockConsole['info'] = (...args) => {+ return Ref.update(lines, Array.appendAll(args));+ };++ const warn: MockConsole['warn'] = (...args) => {+ return Ref.update(lines, Array.appendAll(args));+ };++ const error: MockConsole['error'] = (...args) => {+ return Ref.update(lines, Array.appendAll(args));+ };++ return MockConsole.of({+ [Console.TypeId]: Console.TypeId,+ getLines,+ log,+ info,+ warn,+ error,+ unsafe: globalThis.console,+ assert: () => Effect.void,+ clear: Effect.void,+ count: () => Effect.void,+ countReset: () => Effect.void,+ debug: () => Effect.void,+ dir: () => Effect.void,+ dirxml: () => Effect.void,+ group: () => Effect.void,+ groupEnd: Effect.void,+ table: () => Effect.void,+ time: () => Effect.void,+ timeEnd: () => Effect.void,+ timeLog: () => Effect.void,+ trace: () => Effect.void,+ });+});++export const getLines = (+ params?: Partial<{+ readonly stripAnsi?: boolean;+ }>+): Effect.Effect<ReadonlyArray<string>> =>+ Effect.consoleWith(_console => (_console as MockConsole).getLines(params));diff --git a/ts/packages/cli/test/__utils__/services/mock-terminal.ts b/ts/packages/cli/test/__utils__/services/mock-terminal.tsnew file mode 100644index 000000000..aeb0d60a7--- /dev/null+++ b/ts/packages/cli/test/__utils__/services/mock-terminal.ts@@ -0,0 +1,114 @@+// Copied from https://github.com/Effect-TS/effect/blob/a2d57c9ac596445009ca12859b78e00e5d89b936/packages/cli/test/services/MockTerminal.ts++import * as Terminal from '@effect/platform/Terminal';+import * as Array from 'effect/Array';+import * as Console from 'effect/Console';+import * as Context from 'effect/Context';+import * as Effect from 'effect/Effect';+import * as Layer from 'effect/Layer';+import * as Option from 'effect/Option';+import * as Queue from 'effect/Queue';++// =============================================================================+// Models+// =============================================================================++export interface MockTerminal extends Terminal.Terminal {+ readonly inputText: (text: string) => Effect.Effect<void>;+ readonly inputKey: (+ key: string,+ modifiers?: Partial<MockTerminal.Modifiers>+ ) => Effect.Effect<void>;+}++export declare namespace MockTerminal {+ export interface Modifiers {+ readonly ctrl: boolean;+ readonly meta: boolean;+ readonly shift: boolean;+ }+}++// =============================================================================+// Context+// =============================================================================++export const MockTerminal = Context.GenericTag<Terminal.Terminal, MockTerminal>(+ '@effect/platform/Terminal'+);++// =============================================================================+// Constructors+// =============================================================================++export const make = Effect.gen(function* (_) {+ const queue = yield* _(+ Effect.acquireRelease(Queue.unbounded<Terminal.UserInput>(), Queue.shutdown)+ );++ const inputText: MockTerminal['inputText'] = (text: string) => {+ const inputs = Array.map(text.split(''), key => toUserInput(key));+ return Queue.offerAll(queue, inputs).pipe(Effect.asVoid);+ };++ const inputKey: MockTerminal['inputKey'] = (+ key: string,+ modifiers?: Partial<MockTerminal.Modifiers>+ ) => {+ const input = toUserInput(key, modifiers);+ return Queue.offer(queue, input).pipe(Effect.asVoid);+ };++ const display: MockTerminal['display'] = input => Console.log(input);++ const readInput: MockTerminal['readInput'] = Queue.take(queue).pipe(+ Effect.filterOrFail(+ input => !shouldQuit(input),+ () => new Terminal.QuitException()+ ),+ Effect.timeoutFail({+ duration: '2 seconds',+ onTimeout: () => new Terminal.QuitException(),+ })+ );++ return MockTerminal.of({+ columns: Effect.succeed(80),+ display,+ readInput,+ readLine: Effect.succeed(''),+ inputKey,+ inputText,+ });+});++// =============================================================================+// Layer+// =============================================================================++export const layer = Layer.scoped(MockTerminal, make);++// =============================================================================+// Accessors+// =============================================================================++export const { columns, readInput, readLine } = Effect.serviceConstants(MockTerminal);+export const { inputKey, inputText } = Effect.serviceFunctions(MockTerminal);++// =============================================================================+// Utilities+// =============================================================================++const shouldQuit = (input: Terminal.UserInput): boolean =>+ input.key.ctrl && (input.key.name === 'c' || input.key.name === 'd');++const toUserInput = (+ key: string,+ modifiers: Partial<MockTerminal.Modifiers> = {}+): Terminal.UserInput => {+ const { ctrl = false, meta = false, shift = false } = modifiers;+ return {+ input: Option.some(key),+ key: { name: key, ctrl, meta, shift },+ };+};diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.tsnew file mode 100644index 000000000..575c0c3f6--- /dev/null+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts@@ -0,0 +1,187 @@+import path from 'node:path';+import * as tempy from 'tempy';+import { CliApp } from '@effect/cli';+import { FileSystem } from '@effect/platform';+import { BunFileSystem, BunContext, BunPath } from '@effect/platform-bun';+import { Console, DateTime, Effect, Layer, Logger, LogLevel, Schedule } from 'effect';+import { CliConfigLive } from 'src/bin';+import * as MockConsole from './mock-console';+import * as MockTerminal from './mock-terminal';+import type { Toolkits } from 'src/models/toolkits';+import { NodeProcess } from 'src/services/node-process';+import {+ ComposioSessionRepository,+ ComposioToolkitsRepository,+} from 'src/services/composio-clients';+import { EnvLangDetector } from 'src/services/env-lang-detector';+import type { Tools } from 'src/models/tools';+import type { TriggerTypes } from 'src/models/trigger-types';++interface TestLiveInput {+ /**+ * Fixture to use in test.+ */+ fixture?: string;++ /**+ * Mock toolkit-related data to use in test.+ */+ toolkitsData?: {+ toolkits?: Toolkits;+ tools?: Tools;+ triggerTypes?: TriggerTypes;+ };+}++/**+ * Effect layer that injects all the services needed for tests, using mocks to avoid+ * side-effects like unwanted HTTP requests to remote services.+ */+export const TestLayer = (input?: TestLiveInput) =>+ Effect.gen(function* () {+ const defaultAppClientData = {+ toolkits: [],+ tools: [],+ triggerTypes: [],+ } satisfies TestLiveInput['toolkitsData'];+ const { fixture, toolkitsData } = Object.assign(+ { fixture: undefined, toolkitsData: defaultAppClientData },+ input+ );++ const tempDir = tempy.temporaryDirectory({ prefix: 'test' });+ const cwd = (yield* setupFixtureFolder({ fixture, tempDir })) ?? tempDir;++ const composioToolkitsRepositoryTest = new ComposioToolkitsRepository({+ getToolkits: () => Effect.succeed(toolkitsData.toolkits),+ getTools: () => Effect.succeed(toolkitsData.tools),+ getTriggerTypes: () => Effect.succeed(toolkitsData.triggerTypes),+ });+ const ComposioToolkitsRepositoryTest = Layer.succeed(+ ComposioToolkitsRepository,+ composioToolkitsRepositoryTest+ );++ const ComposioSessionRepositoryTest = yield* setupComposioSessionRepository();++ // Mock `node:process`+ const nodeProcessTest = new NodeProcess({+ cwd,+ platform: 'darwin',+ arch: 'arm64',+ });+ const NodeProcessTest = Layer.succeed(NodeProcess, nodeProcessTest);++ const MockConsoleTestLive = yield* MockConsole.make;++ const layers = Layer.mergeAll(+ Console.setConsole(MockConsoleTestLive),+ NodeProcessTest,+ CliConfigLive,+ ComposioSessionRepositoryTest,+ ComposioToolkitsRepositoryTest,+ EnvLangDetector.Default,+ BunFileSystem.layer,+ BunContext.layer,+ MockTerminal.layer,+ BunPath.layer+ );++ return layers;+ }).pipe(Logger.withMinimumLogLevel(LogLevel.Info), Layer.unwrapEffect);++// Run @effect/vitest suite with TestLive layer+export const runEffect =+ (input?: TestLiveInput) =>+ <E, A>(self: Effect.Effect<A, E, CliApp.CliApp.Environment>): Promise<A> =>+ Effect.provide(self, TestLayer(input)).pipe(Effect.runPromise);++function setupFixtureFolder({ fixture, tempDir }: { fixture?: string; tempDir: string }) {+ return Effect.gen(function* () {+ if (fixture === undefined) {+ return;+ }++ const fs = yield* FileSystem.FileSystem;++ const realFixturePath = path.resolve(+ new URL('.', import.meta.url).pathname,+ '..',+ '..',+ '__fixtures__',+ fixture+ );+ const tmpFixturesPath = path.join(tempDir, 'test', '__fixtures__', fixture);++ yield* Effect.logDebug(`Using fixture at: ${tmpFixturesPath}`);++ // Retry the task with a delay between retries and a maximum of 3 retries+ const policy = Schedule.addDelay(Schedule.recurs(3), () => '100 millis');++ // If all retries fail, run the fallback effect+ const task = Effect.gen(function* () {+ yield* fs.makeDirectory(tmpFixturesPath, { recursive: true });+ yield* fs.copy(realFixturePath, tmpFixturesPath);+ });++ const repeated = Effect.retryOrElse(policy, () =>+ Effect.die(`Failed to copy fixture to: ${tmpFixturesPath}`)+ );++ yield* repeated(task);++ yield* Effect.logDebug(`Copied fixture to: ${tmpFixturesPath}`);++ return tmpFixturesPath;+ }).pipe(Effect.provide(BunFileSystem.layer));+}++function setupComposioSessionRepository() {+ return Effect.gen(function* () {+ const now = yield* DateTime.now;+ const sessionId = 'te00st11-d0c4-4efa-8117-c638886063e0';+ const sessionCode = '001122';+ const expiresAt = DateTime.add(now, { minutes: 10 });++ const accountName = 'test-name';+ const accountId = 'test-id';+ const accountEmail = '[email protected]';++ const account = {+ name: accountName,+ id: accountId,+ email: accountEmail,+ };++ const composioSessionRepositoryTest = new ComposioSessionRepository({+ createSession: () =>+ Effect.succeed({+ id: sessionId,+ code: sessionCode,+ expiresAt,+ status: 'pending',+ }),+ retrieveSession: () =>+ Effect.succeed({+ id: sessionId,+ code: sessionCode,+ expiresAt,+ status: 'pending',+ }),+ linkSession: () =>+ Effect.succeed({+ id: sessionId,+ code: sessionCode,+ expiresAt,+ status: 'linked',+ account,+ }),+ });+ const ComposioSessionRepositoryTest = Layer.succeed(+ ComposioSessionRepository,+ composioSessionRepositoryTest+ );++ return ComposioSessionRepositoryTest;+ });+}diff --git a/ts/packages/cli/test/__utils__/typescript-compiler.ts b/ts/packages/cli/test/__utils__/typescript-compiler.tsnew file mode 100644index 000000000..0afd8d439--- /dev/null+++ b/ts/packages/cli/test/__utils__/typescript-compiler.ts@@ -0,0 +1,95 @@+import { describe, it, expect } from 'vitest';+import ts from 'typescript';++interface AssertTypeScriptIsValidInput {+ files: {+ [filename: string]: string;+ };+}++/**+ * Asserts that the provided TypeScript code is syntactically and semantically valid.+ */+export function assertTypeScriptIsValid({ files }: AssertTypeScriptIsValidInput) {+ const compilerOptions = {+ noEmit: true,+ strict: true,+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.ES2022,+ skipLibCheck: false,+ types: [],+ lib: [],+ jsx: ts.JsxEmit.None,+ isolatedModules: true,+ allowJs: false,+ moduleResolution: ts.ModuleResolutionKind.Bundler,+ allowImportingTsExtensions: true,+ } satisfies ts.CompilerOptions;++ const virtualFileMap = new Map(+ Object.entries(files).map(+ ([filename, code]) =>+ [+ filename,+ ts.createSourceFile(filename, code, compilerOptions.target, true, ts.ScriptKind.TS),+ ] as const+ )+ );+ const virtualFileNames = Array.from(virtualFileMap.keys());++ const tsHost = ts.createCompilerHost(compilerOptions);+ tsHost.getSourceFile = (filename, _languageVersion) => {+ if (virtualFileMap.has(filename)) {+ return virtualFileMap.get(filename);+ }++ if (virtualFileMap.has(`./${filename}`)) {+ return virtualFileMap.get(filename);+ }++ throw new Error(`Unexpected filename ${filename}`);+ };++ const program = ts.createProgram(virtualFileNames, compilerOptions, tsHost);++ // Check for syntax or semantic errors+ const diagnostics = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics()];++ // Assert that there are no TypeScript errors+ expect(diagnostics).toEqual([]);+}++if (import.meta.vitest) {+ describe('assertTypeScriptIsValid', () => {+ it('[Given] valid TypeScript code [Then] no errors are found', () => {+ const code = /* typescript */ `+ export const id = <T>(x: T): T => x;+ `;+ assertTypeScriptIsValid({ files: { 'index.ts': code } });+ });++ it('[Given] valid TypeScript code with resolvable imports [Then] no errors are found', () => {+ const doubleSource = /* typescript */ `+ import { multiply } from './multiply.ts';++ export const double = (x: number) => multiply(x, 2);+ `;+ const multiplySource = /* typescript */ `+ export const multiply = (x: number, y: number) => x * y;+ `;++ assertTypeScriptIsValid({+ files: { './index.ts': doubleSource, './multiply.ts': multiplySource },+ });+ });++ it('[Given] invalid TypeScript code [Then] errors are found', () => {+ const code = /* typescript */ `+ export const id<T> = (x: T) => T: x;+ `;+ expect(() => {+ assertTypeScriptIsValid({ files: { 'index.ts': code } });+ }).toThrowError();+ });+ });+}diff --git a/ts/packages/cli/test/src/commands/$default.cmd.test.ts b/ts/packages/cli/test/src/commands/$default.cmd.test.tsnew file mode 100644index 000000000..7b6486259--- /dev/null+++ b/ts/packages/cli/test/src/commands/$default.cmd.test.ts@@ -0,0 +1,102 @@+import { describe, expect, layer } from '@effect/vitest';+import { Effect, Fiber } from 'effect';+import { ValidationError, HelpDoc } from '@effect/cli';+import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';+import { sanitize } from 'test/__utils__/sanitize';++describe('CLI: composio', () => {+ layer(TestLive())(it => {+ it.effect.skip('[Given] unknown argument [Then] print error message', () =>+ Effect.gen(function* () {+ const args = ['--bar'];+ const fiber = yield* Effect.fork(cli(args));+ yield* Fiber.join(fiber);++ const result = yield* Effect.flip(fiber);+ expect(result).toEqual(+ ValidationError.invalidValue(HelpDoc.p("Received unknown argument: '--bar'"))+ );+ })+ );++ it.effect('[Given] --help flag [Then] prints help message', () =>+ Effect.gen(function* () {+ const args = ['--help'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');++ expect(yield* sanitize(output)).toMatchInlineSnapshot(`+ "[0;1m[0;37;1mcomposio[0;1m[0m++ composio <VERSION>++ [0;1mUSAGE[0m++ $ composio [--log-level all | trace | debug | info | warning | error | fatal | none]++ [0;1mDESCRIPTION[0m++ Composio CLI - A tool for managing Python and TypeScript composio.dev projects.++ [0;1mOPTIONS[0m++ [0;1m--log-level all | trace | debug | info | warning | error | fatal | none[0m++ One of the following: all, trace, debug, info, warning, error, fatal, none++ Define log level++ This setting is optional.++ [0;1mCOMMANDS[0m++ - version Display your account information.++ [0;1mCOMMANDS[0m++ - version Display your account information.++ - whoami Display your account information.++ - login Log in to the Composio SDK.++ - generate [(-o, --output-dir directory)] Updates the local type stubs with the latest app data, automatically detecting the language of the project in the current working directory (TypeScript | Python).++ - py Handle Python projects.++ - py generate [(-o, --output-dir directory)] Updates the local type stubs with the latest app data.++ - ts Handle TypeScript projects.++ - ts generate [(-o, --output-dir directory)] [--single-file] Updates the local type stubs with the latest app data.+ "+ `);+ })+ );++ it.effect("[Given] --version flag [Then] prints composio's version from package.json", () =>+ Effect.gen(function* () {+ const args = ['--version'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain(pkg.version);+ })+ );++ // it.effect('[Pressing] CTRL+C [Then] quit wizard mode', () =>+ // Effect.gen(function* () {+ // const args = ['--wizard'];++ // const fiber = yield* Effect.fork(cli(args));+ // yield* MockTerminal.inputKey('c', { ctrl: true });+ // yield* Fiber.join(fiber);++ // const lines = yield* MockConsole.getLines();+ // const output = lines.join('\n');+ // expect(output).toContain('Quitting wizard mode...');+ // })+ // );+ });+});diff --git a/ts/packages/cli/test/src/commands/generate.cmd.test.ts b/ts/packages/cli/test/src/commands/generate.cmd.test.tsnew file mode 100644index 000000000..0889fcc2d--- /dev/null+++ b/ts/packages/cli/test/src/commands/generate.cmd.test.ts@@ -0,0 +1,37 @@+import { describe, expect, layer } from '@effect/vitest';+import { Effect } from 'effect';+import { cli, TestLive, MockConsole } from 'test/__utils__';++describe('CLI: composio generate', () => {+ layer(+ TestLive({+ fixture: 'python-project',+ })+ )(it => {+ it.effect('[Given] a valid Python project in cwd [Then] it detects its language', () =>+ Effect.gen(function* () {+ const args = ['generate'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain('Project type detected: Python');+ })+ );+ });++ layer(+ TestLive({+ fixture: 'typescript-project',+ })+ )(it => {+ it.effect('[Given] a valid TypeScript project in cwd [Then] it detects its language', () =>+ Effect.gen(function* () {+ const args = ['generate'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain('Project type detected: TypeScript');+ })+ );+ });+});diff --git a/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts b/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.tsnew file mode 100644index 000000000..29b0f608e--- /dev/null+++ b/ts/packages/cli/test/src/commands/py/py.generate.cmd.test.ts@@ -0,0 +1,219 @@+import path from 'node:path';+import { describe, expect, layer, vi } from '@effect/vitest';+import { Effect } from 'effect';+import { FileSystem } from '@effect/platform';+import { cli, TestLive } from 'test/__utils__';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';+import { NodeProcess } from 'src/services/node-process';++describe('CLI: composio py generate', () => {+ const appClientData = {+ toolkits: makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack',+ slug: 'slack',+ },+ ]),+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ };++ layer(+ TestLive({+ fixture: 'python-project',+ toolkitsData: appClientData,+ })+ )(it => {+ describe('[Given] valid fetched app data', () => {+ it.effect(+ '[Given] no arguments [Then] it generates type stubs relative to the cache directory',+ () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ vi.stubEnv('COMPOSIO_CACHE_DIR', cwd);++ const args = ['py', 'generate'];+ yield* cli(args);++ const outputDir = path.join(cwd, '.generated', 'composio-py');++ const gmailSourceCode = yield* fs.readFileString(path.join(outputDir, 'gmail.py'));+ const slackSourceCode = yield* fs.readFileString(path.join(outputDir, 'slack.py'));++ expect(gmailSourceCode).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class GMAIL:+ """Map of Composio's GMAIL toolkit."""++ slug: str = "gmail"++ class tools:+ CREATE_EMAIL_DRAFT = "GMAIL_CREATE_EMAIL_DRAFT"+ DELETE_MESSAGE = "GMAIL_DELETE_MESSAGE"+ FETCH_EMAILS = "GMAIL_FETCH_EMAILS"++ class triggers:+ NEW_GMAIL_MESSAGE = "GMAIL_NEW_GMAIL_MESSAGE"+ "+ `);+ expect(slackSourceCode).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class SLACK:+ """Map of Composio's SLACK toolkit."""++ slug: str = "slack"++ class tools:+ pass++ class triggers:+ pass+ "+ `);+ })+ );++ it.effect(+ '[Given] --output-dir [Then] it generates type stubs relative to the given output directory',+ () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ const outputDirArg = path.join('.generated', 'composio-py');++ const args = ['py', 'generate', '--output-dir', outputDirArg];+ yield* cli(args);++ const outputDir = path.join(cwd, outputDirArg);++ const gmailSourceCode = yield* fs.readFileString(path.join(outputDir, 'gmail.py'));+ const slackSourceCode = yield* fs.readFileString(path.join(outputDir, 'slack.py'));++ expect(gmailSourceCode).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class GMAIL:+ """Map of Composio's GMAIL toolkit."""++ slug: str = "gmail"++ class tools:+ CREATE_EMAIL_DRAFT = "GMAIL_CREATE_EMAIL_DRAFT"+ DELETE_MESSAGE = "GMAIL_DELETE_MESSAGE"+ FETCH_EMAILS = "GMAIL_FETCH_EMAILS"++ class triggers:+ NEW_GMAIL_MESSAGE = "GMAIL_NEW_GMAIL_MESSAGE"+ "+ `);+ expect(slackSourceCode).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class SLACK:+ """Map of Composio's SLACK toolkit."""++ slug: str = "slack"++ class tools:+ pass++ class triggers:+ pass+ "+ `);+ })+ );++ it.effect('[Given] --single-file [Then] it generates type stubs in a single file', () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ vi.stubEnv('COMPOSIO_CACHE_DIR', cwd);++ const args = ['ts', 'generate', '--single-file'];+ yield* cli(args);++ const outputDir = path.join(cwd, '.generated', 'composio-ts');++ expect(yield* fs.exists(path.join(outputDir, 'index.ts'))).toBe(true);++ const indexSourceCode = yield* fs.readFileString(path.join(outputDir, 'index.ts'));++ expect(indexSourceCode).toMatchInlineSnapshot(`+ "/**+ * Auto-generated by Composio CLI. Do not modify manually.+ */++ /**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }++ /**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]+++ "+ `);+ })+ );+ });+ });+});diff --git a/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts b/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.tsnew file mode 100644index 000000000..88597065a--- /dev/null+++ b/ts/packages/cli/test/src/commands/ts/ts.generate.cmd.test.ts@@ -0,0 +1,300 @@+import path from 'node:path';+import { describe, expect, layer, vi } from '@effect/vitest';+import { Effect } from 'effect';+import { FileSystem } from '@effect/platform';+import { cli, TestLive } from 'test/__utils__';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';+import { NodeProcess } from 'src/services/node-process';+import { assertTypeScriptIsValid } from 'test/__utils__/typescript-compiler';++describe('CLI: composio ts generate', () => {+ const appClientData = {+ toolkits: makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack',+ slug: 'slack',+ },+ ]),+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ };++ layer(+ TestLive({+ fixture: 'typescript-project',+ toolkitsData: appClientData,+ })+ )(it => {+ describe('[Given] valid fetched app data', () => {+ it.effect(+ '[Given] no arguments [Then] it generates type stubs relative to the cache directory',+ () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ vi.stubEnv('COMPOSIO_CACHE_DIR', cwd);++ const args = ['ts', 'generate'];+ yield* cli(args);++ const outputDir = path.join(cwd, '.generated', 'composio-ts');++ const gmailSourceCode = yield* fs.readFileString(path.join(outputDir, 'gmail.ts'));+ const slackSourceCode = yield* fs.readFileString(path.join(outputDir, 'slack.ts'));+ const indexSourceCode = yield* fs.readFileString(path.join(outputDir, 'index.ts'));++ expect(gmailSourceCode).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }+ "+ `);+ expect(slackSourceCode).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ expect(indexSourceCode).toMatchInlineSnapshot(`+ "/**+ * Auto-generated by Composio CLI. Do not modify manually.+ */++ import { GMAIL } from "./gmail.ts"+ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({ files: { './gmail.ts': gmailSourceCode } });+ assertTypeScriptIsValid({ files: { './slack.ts': slackSourceCode } });+ assertTypeScriptIsValid({+ files: {+ './index.ts': indexSourceCode,+ './gmail.ts': gmailSourceCode,+ './slack.ts': slackSourceCode,+ },+ });+ })+ );++ it.effect(+ '[Given] --output-dir [Then] it generates type stubs relative to the given output directory',+ () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ const outputDirArg = path.join('.generated', 'composio-ts');++ const args = ['ts', 'generate', '--output-dir', outputDirArg];+ yield* cli(args);++ const outputDir = path.join(cwd, outputDirArg);++ const gmailSourceCode = yield* fs.readFileString(path.join(outputDir, 'gmail.ts'));+ const slackSourceCode = yield* fs.readFileString(path.join(outputDir, 'slack.ts'));+ const indexSourceCode = yield* fs.readFileString(path.join(outputDir, 'index.ts'));++ expect(gmailSourceCode).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }+ "+ `);+ expect(slackSourceCode).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ expect(indexSourceCode).toMatchInlineSnapshot(`+ "/**+ * Auto-generated by Composio CLI. Do not modify manually.+ */++ import { GMAIL } from "./gmail.ts"+ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({ files: { './gmail.ts': gmailSourceCode } });+ assertTypeScriptIsValid({ files: { './slack.ts': slackSourceCode } });+ assertTypeScriptIsValid({+ files: {+ './index.ts': indexSourceCode,+ './gmail.ts': gmailSourceCode,+ './slack.ts': slackSourceCode,+ },+ });+ })+ );++ it.effect('[Given] --single-file [Then] it generates type stubs in a single file', () =>+ Effect.gen(function* () {+ const process = yield* NodeProcess;+ const cwd = process.cwd;+ const fs = yield* FileSystem.FileSystem;++ vi.stubEnv('COMPOSIO_CACHE_DIR', cwd);++ const args = ['ts', 'generate', '--single-file'];+ yield* cli(args);++ const outputDir = path.join(cwd, '.generated', 'composio-ts');++ expect(yield* fs.exists(path.join(outputDir, 'index.ts'))).toBe(true);++ const indexSourceCode = yield* fs.readFileString(path.join(outputDir, 'index.ts'));++ expect(indexSourceCode).toMatchInlineSnapshot(`+ "/**+ * Auto-generated by Composio CLI. Do not modify manually.+ */++ /**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }++ /**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]+++ "+ `);++ assertTypeScriptIsValid({ files: { './index.ts': indexSourceCode } });+ })+ );+ });+ });+});diff --git a/ts/packages/cli/test/src/commands/version.test.ts b/ts/packages/cli/test/src/commands/version.test.tsnew file mode 100644index 000000000..9f2598065--- /dev/null+++ b/ts/packages/cli/test/src/commands/version.test.ts@@ -0,0 +1,30 @@+import { vi, describe, expect, layer } from '@effect/vitest';+import { Effect } from 'effect';+import { cli, pkg, TestLive, MockConsole } from 'test/__utils__';++describe('CLI: composio', () => {+ layer(TestLive())(it => {+ it.effect("[Given] no arguments [Then] prints composio's version from package.json", () =>+ Effect.gen(function* () {+ const args = ['version'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain(pkg.version);+ })+ );++ it.effect('[Given] DEBUG_OVERRIDE_VERSION env var [Then] prints overridden version', () =>+ Effect.gen(function* () {+ const expectedVersion = '1.2.3-test';+ vi.stubEnv('DEBUG_OVERRIDE_VERSION', expectedVersion);++ const args = ['version'];+ yield* cli(args);+ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain(expectedVersion);+ })+ );+ });+});diff --git a/ts/packages/cli/test/src/commands/whoami.cmd.test.ts b/ts/packages/cli/test/src/commands/whoami.cmd.test.tsnew file mode 100644index 000000000..8451c4514--- /dev/null+++ b/ts/packages/cli/test/src/commands/whoami.cmd.test.ts@@ -0,0 +1,25 @@+import { describe, expect, layer } from '@effect/vitest';+import { ConfigProvider, Effect, Layer } from 'effect';+import { cli, TestLive, MockConsole } from 'test/__utils__';++describe('CLI: composio whoami', () => {+ // Create a mock config provider using a map with test data.+ // Note: `process.env.COMPOSIO_API_KEY` is interpreted as Config.string('API_KEY')+ // after prefix stripping+ const mockConfigProvider = ConfigProvider.fromMap(+ new Map([['API_KEY', 'api_key_from_test_env']])+ );++ layer(TestLive().pipe(Layer.provide(Layer.setConfigProvider(mockConfigProvider))))(it => {+ it.effect('[Given] `COMPOSIO_API_KEY` env var [Then] prints it in stdout', () =>+ Effect.gen(function* () {+ const args = ['whoami'];+ yield* cli(args);++ const lines = yield* MockConsole.getLines();+ const output = lines.join('\n');+ expect(output).toContain(`API KEY: api_key_from_test_env`);+ })+ );+ });+});diff --git a/ts/packages/cli/test/src/generation/python/generate-toolkit-source.test.ts b/ts/packages/cli/test/src/generation/python/generate-toolkit-source.test.tsnew file mode 100644index 000000000..d289dac21--- /dev/null+++ b/ts/packages/cli/test/src/generation/python/generate-toolkit-source.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from 'vitest';+import { generatePythonToolkitSources } from 'src/generation/python/generate-toolkit-sources';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';++describe('generatePythonToolkitSources', () => {+ it('[Given] empty toolkits, tools, triggerTypes [Then] it returns an empty array', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const sources = generatePythonToolkitSources(index);++ expect(sources).toEqual([]);+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it returns a single Python source file', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const sources = generatePythonToolkitSources(index);+ expect(sources).toHaveLength(1);+ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('slack.py');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class SLACK:+ """Map of Composio's SLACK toolkit."""++ slug: str = "slack"++ class tools:+ pass++ class triggers:+ pass+ "+ `);+ });++ it('[Given] toolkits with tools and triggerTypes [Then] it returns a Python source file for each toolkit', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const sources = generatePythonToolkitSources(index);+ expect(sources).toHaveLength(2);++ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('gmail.py');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class GMAIL:+ """Map of Composio's GMAIL toolkit."""++ slug: str = "gmail"++ class tools:+ CREATE_EMAIL_DRAFT = "GMAIL_CREATE_EMAIL_DRAFT"+ DELETE_MESSAGE = "GMAIL_DELETE_MESSAGE"+ FETCH_EMAILS = "GMAIL_FETCH_EMAILS"++ class triggers:+ NEW_GMAIL_MESSAGE = "GMAIL_NEW_GMAIL_MESSAGE"+ "+ `);++ expect(sources[1]).toHaveLength(2);+ expect(sources[1][0]).toBe('slack.py');+ expect(sources[1][1]).toMatchInlineSnapshot(`+ "# Auto-generated by Composio CLI via \`composio py generate\`.+ # Do not modify manually.++ class SLACK:+ """Map of Composio's SLACK toolkit."""++ slug: str = "slack"++ class tools:+ pass++ class triggers:+ pass+ "+ `);+ });+});diff --git a/ts/packages/cli/test/src/generation/toolkit-index.test.ts b/ts/packages/cli/test/src/generation/toolkit-index.test.tsnew file mode 100644index 000000000..ceb55a047--- /dev/null+++ b/ts/packages/cli/test/src/generation/toolkit-index.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';++describe('createToolkitIndex', () => {+ it('[Given] empty toolkits, tools, triggerTypes [Then] it returns an empty index', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ expect(index).toEqual({});+ });++ it('[Given] only toolkits and no tools or triggerTypes [Then] it returns an index with empty tools and triggerTypes', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ expect(index).toEqual({+ GMAIL: {+ slug: 'gmail',+ tools: {},+ triggerTypes: {},+ },+ SLACK: {+ slug: 'slack',+ tools: {},+ triggerTypes: {},+ },+ });+ });++ it('[Given] valid toolkits, tools, triggerTypes [Then] it builds an index based on toolkits', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const tools = ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'];+ const triggerTypes = ['GMAIL_NEW_GMAIL_MESSAGE'];++ const index = createToolkitIndex({+ toolkits,+ tools,+ triggerTypes,+ });++ expect(index).toEqual({+ GMAIL: {+ slug: 'gmail',+ tools: {+ CREATE_EMAIL_DRAFT: 'GMAIL_CREATE_EMAIL_DRAFT',+ DELETE_MESSAGE: 'GMAIL_DELETE_MESSAGE',+ FETCH_EMAILS: 'GMAIL_FETCH_EMAILS',+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: 'GMAIL_NEW_GMAIL_MESSAGE',+ },+ },+ SLACK: {+ slug: 'slack',+ tools: {},+ triggerTypes: {},+ },+ });+ });+});diff --git a/ts/packages/cli/test/src/generation/typescript/generate-index-source.test.ts b/ts/packages/cli/test/src/generation/typescript/generate-index-source.test.tsnew file mode 100644index 000000000..60fe27871--- /dev/null+++ b/ts/packages/cli/test/src/generation/typescript/generate-index-source.test.ts@@ -0,0 +1,312 @@+import { describe, expect, it } from 'vitest';+import { generateIndexSource } from 'src/generation/typescript/generate-index-source';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';+import { assertTypeScriptIsValid } from 'test/__utils__/typescript-compiler';++describe('generateTypeScriptToolkitSources', () => {+ describe('with a single emitted file', () => {+ const _params = {+ outputDir: '<cwd>',+ emitSingleFile: true,+ };++ describe('with banner', () => {+ const params = {+ ..._params,+ banner: '<<< Some banner that will appear in a comment >>>',+ };++ it('[Given] empty toolkits, tools, triggerTypes [Then] it creates a valid but empty index map', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const source = generateIndexSource(params)(index);++ expect(source).not.includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Map of Composio toolkits to actions.+ */+ export const composio = {}++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit = never++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({ files: { 'index.ts': source } });+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it creates an index map with no imports, with unrelesolved references, and with no banner', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const source = generateIndexSource(params)(index);++ expect(source).not.includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);+ });++ it('[Given] multiple toolkits with tools and triggerTypes [Then] it creates an index map with no imports, with unrelesolved references, and with no banner', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const source = generateIndexSource(params)(index);++ expect(source).not.includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);+ });+ });+ });++ describe('with multiple emitted files', () => {+ const _params = {+ outputDir: '<cwd>',+ emitSingleFile: false,+ };++ describe('with banner', () => {+ const params = {+ ..._params,+ banner: 'Some banner that will appear in a comment',+ };++ it('[Given] empty toolkits, tools, triggerTypes [Then] it creates a valid but empty index map', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const source = generateIndexSource(params)(index);++ expect(source).includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {}++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit = never++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({ files: { 'index.ts': source } });+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it creates the index map with imports', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const source = generateIndexSource(params)(index);++ expect(source).includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);+ });++ it('[Given] multiple toolkits with tools and triggerTypes [Then] it creates the index map with imports', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const source = generateIndexSource(params)(index);++ expect(source).includes(params.banner);+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ import { GMAIL } from "./gmail.ts"+ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ GMAIL: GMAIL,+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "GMAIL"+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);+ });+ });+ });+});diff --git a/ts/packages/cli/test/src/generation/typescript/generate-toolkit-source.test.ts b/ts/packages/cli/test/src/generation/typescript/generate-toolkit-source.test.tsnew file mode 100644index 000000000..9fe3d4147--- /dev/null+++ b/ts/packages/cli/test/src/generation/typescript/generate-toolkit-source.test.ts@@ -0,0 +1,232 @@+import { describe, expect, it } from 'vitest';+import { generateTypeScriptToolkitSources } from 'src/generation/typescript/generate-toolkit-sources';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';++describe('generateTypeScriptToolkitSources', () => {+ describe('with a single emitted file', () => {+ const _params = {+ outputDir: '<cwd>',+ emitSingleFile: true,+ };++ describe('with banner', () => {+ const params = {+ ..._params,+ banner: 'Some banner that will appear in a comment',+ };++ it('[Given] empty toolkits, tools, triggerTypes [Then] it returns an empty array', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);++ expect(sources).toEqual([]);+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it returns a single toolkit source file', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);+ expect(sources).toHaveLength(1);+ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('slack.ts');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ });++ it('[Given] toolkits with tools and triggerTypes [Then] it returns a TypeScript source file for each toolkit + the index map', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);+ expect(sources).toHaveLength(2);++ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('gmail.ts');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }+ "+ `);++ expect(sources[1]).toHaveLength(2);+ expect(sources[1][0]).toBe('slack.ts');+ expect(sources[1][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ });+ });+ });++ describe('with multiple emitted files', () => {+ const _params = {+ outputDir: '<cwd>',+ emitSingleFile: false,+ };++ describe('with banner', () => {+ const params = {+ ..._params,+ banner: 'Some banner that will appear in a comment',+ };++ it('[Given] empty toolkits, tools, triggerTypes [Then] it returns an empty array', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);++ expect(sources).toEqual([]);+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it returns a single toolkit source file', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);+ expect(sources).toHaveLength(1);+ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('slack.ts');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ });++ it('[Given] toolkits with tools and triggerTypes [Then] it returns a TypeScript source file for each toolkit + the index map', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Gmail',+ slug: 'gmail',+ },+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const sources = generateTypeScriptToolkitSources(params)(index);+ expect(sources).toHaveLength(2);++ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe('gmail.ts');+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's GMAIL toolkit.+ */+ export const GMAIL = {+ slug: "gmail",+ tools: {+ CREATE_EMAIL_DRAFT: "GMAIL_CREATE_EMAIL_DRAFT",+ DELETE_MESSAGE: "GMAIL_DELETE_MESSAGE",+ FETCH_EMAILS: "GMAIL_FETCH_EMAILS",+ },+ triggerTypes: {+ NEW_GMAIL_MESSAGE: "GMAIL_NEW_GMAIL_MESSAGE",+ },+ }+ "+ `);++ expect(sources[1]).toHaveLength(2);+ expect(sources[1][0]).toBe('slack.ts');+ expect(sources[1][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ });+ });+ });+});diff --git a/ts/packages/cli/test/src/generation/typescript/generate.test.ts b/ts/packages/cli/test/src/generation/typescript/generate.test.tsnew file mode 100644index 000000000..fb001b9b7--- /dev/null+++ b/ts/packages/cli/test/src/generation/typescript/generate.test.ts@@ -0,0 +1,202 @@+import { describe, expect, it } from 'vitest';+import { createToolkitIndex } from 'src/generation/create-toolkit-index';+import { generateTypeScriptSources } from 'src/generation/typescript/generate';+import { makeTestToolkits } from 'test/__utils__/models/toolkits';+import path from 'path';+import { assertTypeScriptIsValid } from 'test/__utils__/typescript-compiler';++describe('generateTypeScriptSources', () => {+ describe('with multiple emitted files', () => {+ const _params = {+ outputDir: '<cwd>',+ emitSingleFile: false,+ };++ describe('with banner', () => {+ const params = {+ ..._params,+ banner: 'Some banner that will appear in a comment',+ };++ it('[Given] empty toolkits, tools, triggerTypes [Then] it returns just the index map', () => {+ const index = createToolkitIndex({+ toolkits: [],+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptSources(params)(index);++ expect(sources).toHaveLength(1);+ const [[filename, source]] = sources;++ expect(filename).toBe(path.join(params.outputDir, 'index.ts'));+ expect(source).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {}++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit = never++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({ files: { './index.ts': source } });+ });++ it('[Given] a single toolkit with no tools or triggerTypes [Then] it returns a single toolkit source file + the index map', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: [],+ triggerTypes: [],+ });++ const sources = generateTypeScriptSources(params)(index);+ expect(sources).toHaveLength(2);+ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe(path.join(params.outputDir, 'slack.ts'));+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ assertTypeScriptIsValid({ files: { './slack.ts': sources[0][1] } });++ expect(sources[1]).toHaveLength(2);+ expect(sources[1][0]).toBe(path.join(params.outputDir, 'index.ts'));+ expect(sources[1][1]).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);++ assertTypeScriptIsValid({+ files: { './index.ts': sources[1][1], './slack.ts': sources[0][1] },+ });+ });++ it('[Given] toolkits with tools and triggerTypes [Then] it returns a TypeScript source file for each toolkit + the index map', () => {+ const toolkits = makeTestToolkits([+ {+ name: 'Slack Helper',+ slug: 'slack',+ },+ ]);++ const index = createToolkitIndex({+ toolkits,+ tools: ['GMAIL_CREATE_EMAIL_DRAFT', 'GMAIL_DELETE_MESSAGE', 'GMAIL_FETCH_EMAILS'],+ triggerTypes: ['GMAIL_NEW_GMAIL_MESSAGE'],+ });++ const sources = generateTypeScriptSources(params)(index);+ expect(sources).toHaveLength(2);+ expect(sources[0]).toHaveLength(2);+ expect(sources[0][0]).toBe(path.join(params.outputDir, './slack.ts'));+ expect(sources[0][1]).toMatchInlineSnapshot(`+ "/**+ * Map of Composio's SLACK toolkit.+ */+ export const SLACK = {+ slug: "slack",+ tools: {},+ triggerTypes: {},+ }+ "+ `);+ assertTypeScriptIsValid({ files: { './slack.ts': sources[0][1] } });++ expect(sources[1]).toHaveLength(2);+ expect(sources[1][0]).toBe(path.join(params.outputDir, 'index.ts'));+ expect(sources[1][1]).toMatchInlineSnapshot(`+ "/**+ * Some banner that will appear in a comment+ */++ import { SLACK } from "./slack.ts"++ /**+ * Map of Composio toolkits to actions.+ */+ export const composio = {+ SLACK: SLACK,+ }++ /**+ * Type declarations+ */++ /**+ * Union of all available toolkits.+ */+ export type Toolkit =+ | "SLACK"++ /**+ * Given a toolkit, returns the tools available for that toolkit.+ */+ export type ToolsByToolkit<Toolkit extends keyof (typeof composio)> = typeof composio[Toolkit]++ "+ `);+ assertTypeScriptIsValid({ files: { './index.ts': sources[1][1] } });+ });+ });+ });+});diff --git a/ts/packages/cli/tsconfig.json b/ts/packages/cli/tsconfig.jsonnew file mode 100644index 000000000..55ccfcbd7--- /dev/null+++ b/ts/packages/cli/tsconfig.json@@ -0,0 +1,14 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": ".",+ "paths": {+ "src/*": ["./src/*"],+ "test/*": ["./test/*"],+ "~/*": ["./*"]+ },+ "types": ["@types/bun", "vitest/importMeta"]+ },+ "include": ["src", "test", "scripts"]+}diff --git a/ts/packages/cli/tsconfig.options.json b/ts/packages/cli/tsconfig.options.jsonnew file mode 100644index 000000000..88a2c1586--- /dev/null+++ b/ts/packages/cli/tsconfig.options.json@@ -0,0 +1,28 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "outDir": "./dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true,+ "verbatimModuleSyntax": true,+ "pretty": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUnusedLocals": false,+ "noUnusedParameters": false,+ "plugins": [+ {+ "name": "@effect/language-service"+ }+ ]+ },+ "include": ["src"],+ "exclude": ["**/dist", "test/__fixtures__/**"]+}diff --git a/ts/packages/cli/tsconfig.src.json b/ts/packages/cli/tsconfig.src.jsonnew file mode 100644index 000000000..a5b41d1fa--- /dev/null+++ b/ts/packages/cli/tsconfig.src.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "outDir": "./dist",+ "rootDir": ".",+ "paths": {+ "src/*": ["./src/*"]+ },+ "types": ["@types/bun"]+ },+ "include": ["src"]+}diff --git a/ts/packages/cli/tsconfig.test.json b/ts/packages/cli/tsconfig.test.jsonnew file mode 100644index 000000000..1b2ad574d--- /dev/null+++ b/ts/packages/cli/tsconfig.test.json@@ -0,0 +1,12 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": ".",+ "paths": {+ "src/*": ["./src/*"],+ "test/*": ["./test/*"]+ }+ },+ "include": ["test"]+}diff --git a/ts/packages/cli/tsup.config.ts b/ts/packages/cli/tsup.config.tsnew file mode 100644index 000000000..390e56c88--- /dev/null+++ b/ts/packages/cli/tsup.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: ['src/bin.ts'],+ format: ['esm'],+ dts: true,+ clean: true,+ minify: false,+ outDir: 'dist',+ tsconfig: './tsconfig.src.json',+ banner: {+ js: '#!/usr/bin/env bun',+ },+});diff --git a/ts/packages/cli/vitest.config.ts b/ts/packages/cli/vitest.config.tsnew file mode 100644index 000000000..6f357b0f8--- /dev/null+++ b/ts/packages/cli/vitest.config.ts@@ -0,0 +1,20 @@+import { defineConfig } from 'vitest/config';+import path from 'node:path';++const __dirname = path.resolve(path.dirname(new URL(import.meta.url).pathname));++export default defineConfig({+ resolve: {+ alias: {+ '~': path.resolve(__dirname, './'),+ src: path.resolve(__dirname, './src'),+ test: path.resolve(__dirname, './test'),+ },+ },+ test: {+ typecheck: {+ tsconfig: './tsconfig.test.json',+ },+ includeSource: ['src/**/*.ts', 'test/**/*.ts'],+ },+});diff --git a/ts/packages/core/src/index.ts b/ts/packages/core/src/index.tsindex 71649a896..7abd715b0 100644--- a/ts/packages/core/src/index.ts+++ b/ts/packages/core/src/index.ts@@ -14,6 +14,7 @@ export * from './types/modifiers.types';export * from './types/connectedAccountAuthStates.types';export * from './types/toolkit.types';export * from './types/triggers.types';+export * as constants from './utils/constants';export { default as logger } from './utils/logger';// Error handling exportsdiff --git a/ts/packages/ts-builders/README.md b/ts/packages/ts-builders/README.mdnew file mode 100644index 000000000..d7ca59eda--- /dev/null+++ b/ts/packages/ts-builders/README.md@@ -0,0 +1,23 @@+# @composio/ts-builders++This package provides a set of utilities for programmatically generating TypeScript Abstract Syntax Trees. It is used to generate type stubs for TypeScript projects in the Composio CLI ([@composio/cli](./../cli/README.md)).++## Development++### Installation++```bash+pnpm install+```++### Build++```bash+pnpm build+```++### Test++```bash+pnpm test+```diff --git a/ts/packages/ts-builders/package.json b/ts/packages/ts-builders/package.jsonnew file mode 100644index 000000000..2bc777f2d--- /dev/null+++ b/ts/packages/ts-builders/package.json@@ -0,0 +1,40 @@+{+ "name": "@composio/ts-builders",+ "version": "0.1.24",+ "description": "Fork of @prisma/ts-builders",+ "type": "module",+ "main": "dist/index.js",+ "module": "dist/index.js",+ "types": "dist/index.d.ts",+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ }+ }+ },+ "repository": {+ "type": "git",+ "url": "https://github.com/ComposioHQ/composio.git",+ "directory": "ts/packages/ts-builders"+ },+ "license": "Apache-2.0",+ "devDependencies": {+ "@types/babel__helper-validator-identifier": "^7.15.2",+ "helper-validator-identifier": "link:@types/@babel/helper-validator-identifier",+ "tsup": "^8.4.0",+ "vitest": "^3.1.4"+ },+ "scripts": {+ "build": "tsup",+ "test": "vitest run"+ },+ "files": [+ "dist"+ ],+ "sideEffects": false,+ "dependencies": {+ "@babel/helper-validator-identifier": "^7.27.1"+ }+}diff --git a/ts/packages/ts-builders/src/AnyDeclarationBuilder.ts b/ts/packages/ts-builders/src/AnyDeclarationBuilder.tsnew file mode 100644index 000000000..f0cbd2511--- /dev/null+++ b/ts/packages/ts-builders/src/AnyDeclarationBuilder.ts@@ -0,0 +1,12 @@+import { ClassDeclaration } from './Class';+import { ConstDeclaration } from './ConstDeclaration';+import { InterfaceDeclaration } from './Interface';+import { NamespaceDeclaration } from './NamespaceDeclaration';+import { TypeDeclaration } from './TypeDeclaration';++export type AnyDeclarationBuilder =+ | TypeDeclaration+ | ConstDeclaration+ | InterfaceDeclaration+ | ClassDeclaration+ | NamespaceDeclaration;diff --git a/ts/packages/ts-builders/src/ArraySpread.ts b/ts/packages/ts-builders/src/ArraySpread.tsnew file mode 100644index 000000000..fb4294032--- /dev/null+++ b/ts/packages/ts-builders/src/ArraySpread.ts@@ -0,0 +1,18 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++export class ArraySpread extends TypeBuilder {+ readonly precedence = OperatorPrecedence.ArrayType;++ constructor(private innerType: TypeBuilder) {+ super();+ }+ write(writer: Writer): void {+ writer.write('[...').write(this.innerType).write(']');+ }+}++export function arraySpread(innerType: TypeBuilder) {+ return new ArraySpread(innerType);+}diff --git a/ts/packages/ts-builders/src/ArrayType.test.ts b/ts/packages/ts-builders/src/ArrayType.test.tsnew file mode 100644index 000000000..0e0c03db9--- /dev/null+++ b/ts/packages/ts-builders/src/ArrayType.test.ts@@ -0,0 +1,29 @@+import { expect, test } from 'vitest';++import { array } from './ArrayType';+import { functionType } from './FunctionType';+import { namedType } from './NamedType';+import { objectType } from './ObjectType';+import { stringify } from './stringify';+import { unionType } from './UnionType';++const A = namedType('A');+const B = namedType('B');+const C = namedType('C');++test('simple only', () => {+ expect(stringify(array(A))).toMatchInlineSnapshot(`"A[]"`);+});++test('with object type', () => {+ expect(stringify(array(objectType()))).toMatchInlineSnapshot(`"({})[]"`);+});++test('with function type', () => {+ expect(stringify(array(functionType()))).toMatchInlineSnapshot(`"(() => void)[]"`);+});++test('with union type', () => {+ const union = unionType(A).addVariant(B).addVariant(C);+ expect(stringify(array(union))).toMatchInlineSnapshot(`"(A | B | C)[]"`);+});diff --git a/ts/packages/ts-builders/src/ArrayType.ts b/ts/packages/ts-builders/src/ArrayType.tsnew file mode 100644index 000000000..37790df67--- /dev/null+++ b/ts/packages/ts-builders/src/ArrayType.ts@@ -0,0 +1,20 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class ArrayType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.ArrayType;++ constructor(private elementType: TypeBuilder) {+ super();+ }++ write(writer: Writer): void {+ this.elementType.writeInContext(writer, TypeContext.ArrayElement);+ writer.write('[]');+ }+}++export function array(elementType: TypeBuilder): ArrayType {+ return new ArrayType(elementType);+}diff --git a/ts/packages/ts-builders/src/BasicBuilder.ts b/ts/packages/ts-builders/src/BasicBuilder.tsnew file mode 100644index 000000000..356a88fb1--- /dev/null+++ b/ts/packages/ts-builders/src/BasicBuilder.ts@@ -0,0 +1,5 @@+import { Writer } from './Writer';++export interface BasicBuilder<ContextType = undefined> {+ write(writer: Writer<ContextType>): void;+}diff --git a/ts/packages/ts-builders/src/Class.test.ts b/ts/packages/ts-builders/src/Class.test.tsnew file mode 100644index 000000000..27a2385b8--- /dev/null+++ b/ts/packages/ts-builders/src/Class.test.ts@@ -0,0 +1,68 @@+import { expect, test } from 'vitest';++import { classDeclaration } from './Class';+import { genericParameter } from './GenericParameter';+import { method } from './Method';+import { namedType } from './NamedType';+import { property } from './Property';+import { stringify } from './stringify';++const A = namedType('A');++test('empty', () => {+ const obj = classDeclaration('MyClass');+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class MyClass {}+ "+ `);+});++test('with property', () => {+ const obj = classDeclaration('SomeClass').add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class SomeClass {+ foo: A+ }"+ `);+});++test('with method', () => {+ const obj = classDeclaration('MyClass').add(method('doThing'));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class MyClass {+ doThing(): void+ }"+ `);+});++test('with generic parameter', () => {+ const obj = classDeclaration('SomeClass')+ .addGenericParameter(genericParameter('T').extends(namedType('U')))+ .add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class SomeClass<T extends U> {+ foo: A+ }"+ `);+});++test('extending the type', () => {+ const obj = classDeclaration('SomeClass').extends(namedType('Foo')).add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class SomeClass extends Foo {+ foo: A+ }"+ `);+});++test('extending multiple types', () => {+ const obj = classDeclaration('SomeClass')+ .extends(namedType('Foo'))+ .extends(namedType('Bar'))+ .add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "class SomeClass extends Foo, Bar {+ foo: A+ }"+ `);+});diff --git a/ts/packages/ts-builders/src/Class.ts b/ts/packages/ts-builders/src/Class.tsnew file mode 100644index 000000000..a123de03e--- /dev/null+++ b/ts/packages/ts-builders/src/Class.ts@@ -0,0 +1,72 @@+import { GenericParameter } from './GenericParameter';+import { Method } from './Method';+import { NamedType } from './NamedType';+import { Property } from './Property';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++type ClassItem = Method | Property;++export class ClassDeclaration extends TypeBuilder {+ readonly precedence = OperatorPrecedence.Atomic;+ needsParenthesisWhenIndexed = true;++ private items: ClassItem[] = [];+ private genericParameters: GenericParameter[] = [];+ private extendedTypes: NamedType[] = [];++ constructor(readonly name: string) {+ super();+ }++ add(item: ClassItem): this {+ this.items.push(item);+ return this;+ }++ addMultiple(items: ClassItem[]): this {+ for (const item of items) {+ this.add(item);+ }+ return this;+ }++ addGenericParameter(param: GenericParameter) {+ this.genericParameters.push(param);+ return this;+ }++ extends(type: NamedType) {+ this.extendedTypes.push(type);+ return this;+ }++ write(writer: Writer): void {+ writer.write('class ').write(this.name);+ if (this.genericParameters.length > 0) {+ writer.write('<').writeJoined(', ', this.genericParameters).write('>');+ }++ if (this.extendedTypes.length > 0) {+ writer.write(' extends ').writeJoined(', ', this.extendedTypes);+ }+ if (this.items.length === 0) {+ writer.writeLine(' {}');+ return;+ }++ writer+ .writeLine(' {')+ .withIndent(() => {+ for (const item of this.items) {+ writer.writeLine(item);+ }+ })+ .write('}');+ }+}++export function classDeclaration(name: string) {+ return new ClassDeclaration(name);+}diff --git a/ts/packages/ts-builders/src/ConstDeclaration.test.ts b/ts/packages/ts-builders/src/ConstDeclaration.test.tsnew file mode 100644index 000000000..5bdfd7b83--- /dev/null+++ b/ts/packages/ts-builders/src/ConstDeclaration.test.ts@@ -0,0 +1,22 @@+import { expect, test } from 'vitest';++import { constDeclaration } from './ConstDeclaration';+import { docComment } from './DocComment';+import { namedType } from './NamedType';+import { stringify } from './stringify';++const A = namedType('A');++test('basic', () => {+ expect(stringify(constDeclaration('B', A))).toMatchInlineSnapshot(`"const B: A"`);+});++test('with doc comment', () => {+ const decl = constDeclaration('B', A).setDocComment(docComment('Some important value'));+ expect(stringify(decl)).toMatchInlineSnapshot(`+ "/**+ * Some important value+ */+ const B: A"+ `);+});diff --git a/ts/packages/ts-builders/src/ConstDeclaration.ts b/ts/packages/ts-builders/src/ConstDeclaration.tsnew file mode 100644index 000000000..3878bdbc1--- /dev/null+++ b/ts/packages/ts-builders/src/ConstDeclaration.ts@@ -0,0 +1,42 @@+import type { BasicBuilder } from './BasicBuilder';+import { DocComment } from './DocComment';+import { TypeBuilder } from './TypeBuilder';+import { ValueBuilder } from './ValueBuilder';+import { Writer } from './Writer';++export class ConstDeclaration implements BasicBuilder {+ private docComment?: DocComment;+ private value?: ValueBuilder;++ constructor(+ readonly name: string,+ readonly type?: TypeBuilder+ ) {}++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ setValue(value: ValueBuilder): this {+ this.value = value;+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }+ writer.write('const ').write(this.name);+ if (this.type) {+ writer.write(': ').write(this.type);+ }+ if (this.value) {+ writer.write(' = ').write(this.value);+ }+ }+}++export function constDeclaration(name: string, type?: TypeBuilder) {+ return new ConstDeclaration(name, type);+}diff --git a/ts/packages/ts-builders/src/DocComment.test.ts b/ts/packages/ts-builders/src/DocComment.test.tsnew file mode 100644index 000000000..378cee073--- /dev/null+++ b/ts/packages/ts-builders/src/DocComment.test.ts@@ -0,0 +1,90 @@+import { expect, test } from 'vitest';++import { docComment } from './DocComment';+import { stringify } from './stringify';++test('empty', () => {+ expect(stringify(docComment())).toMatchInlineSnapshot(`+ "/**+ */+ "+ `);+});++test('one line', () => {+ expect(stringify(docComment('I am comment'))).toMatchInlineSnapshot(`+ "/**+ * I am comment+ */+ "+ `);+});++test('multiline', () => {+ expect(stringify(docComment('first\nsecond'))).toMatchInlineSnapshot(`+ "/**+ * first+ * second+ */+ "+ `);+});++test('multiple addText calls', () => {+ const comment = docComment('Line 1').addText('Line 2').addText('Line 3');+ expect(stringify(comment)).toMatchInlineSnapshot(`+ "/**+ * Line 1+ * Line 2+ * Line 3+ */+ "+ `);+});++test('tagged template - empty', () => {+ expect(stringify(docComment``)).toMatchInlineSnapshot(`+ "/**+ */+ "+ `);+});++test('tagged template - spaces only', () => {+ expect(stringify(docComment` `)).toMatchInlineSnapshot(`+ "/**+ */+ "+ `);+});++test('tagged template - with content', () => {+ const comment = docComment`+ This is a multiline comment+ - this line should be indented+ And this should be not+ `;++ expect(stringify(comment)).toMatchInlineSnapshot(`+ "/**+ * This is a multiline comment+ * - this line should be indented+ * And this should be not+ */+ "+ `);+});++test('tagged template - with substitutions', () => {+ const name = 'World';+ const comment = docComment`+ Hello, ${name}!+ `;++ expect(stringify(comment)).toMatchInlineSnapshot(`+ "/**+ * Hello, World!+ */+ "+ `);+});diff --git a/ts/packages/ts-builders/src/DocComment.ts b/ts/packages/ts-builders/src/DocComment.tsnew file mode 100644index 000000000..6c94d3fd7--- /dev/null+++ b/ts/packages/ts-builders/src/DocComment.ts@@ -0,0 +1,95 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';++export class DocComment implements BasicBuilder {+ readonly lines: string[] = [];++ constructor(startingText?: string) {+ if (startingText) {+ this.addText(startingText);+ }+ }++ addText(text: string): this {+ this.lines.push(...text.split('\n'));+ return this;+ }++ write(writer: Writer) {+ writer.writeLine('/**');+ for (const line of this.lines) {+ writer.writeLine(` * ${line}`);+ }+ writer.writeLine(' */');+ return writer;+ }+}++function docComment(strings: TemplateStringsArray, ...args: string[]): DocComment;+function docComment(startingText?: string): DocComment;+function docComment(+ firstParameter: string | TemplateStringsArray | undefined,+ ...args: string[]+): DocComment {+ if (typeof firstParameter === 'string' || typeof firstParameter === 'undefined') {+ return new DocComment(firstParameter);+ }+ return docCommentTag(firstParameter, args);+}++function docCommentTag(strings: TemplateStringsArray, args: string[]) {+ const docComment = new DocComment();+ const fullText = strings+ .flatMap((str, i) => {+ if (i < args.length) {+ return [str, args[i]];+ }+ return [str];+ })+ .join('');+ const lines = trimEmptyLines(fullText.split('\n'));+ if (lines.length === 0) {+ return docComment;+ }+ const indent = getIndent(lines[0]);+ for (const line of lines) {+ docComment.addText(line.slice(indent));+ }+ return docComment;+}++function trimEmptyLines(lines: string[]): string[] {+ const firstLine = findFirstNonEmptyLine(lines);+ const lastLine = findLastNonEmptyLine(lines);+ if (firstLine === -1 || lastLine === -1) {+ // all lines are empty+ return [];+ }+ return lines.slice(firstLine, lastLine + 1);+}++function findFirstNonEmptyLine(lines: string[]) {+ return lines.findIndex(line => !isEmptyLine(line));+}++function findLastNonEmptyLine(lines: string[]) {+ let i = lines.length - 1;+ while (i > 0 && isEmptyLine(lines[i])) {+ i--;+ }+ return i;+}++function isEmptyLine(line: string) {+ return line.trim().length === 0;+}++function getIndent(line: string): number {+ let indent = 0;+ while (line[indent] === ' ') {+ indent++;+ }+ return indent;+}++export { docComment };diff --git a/ts/packages/ts-builders/src/Export.ts b/ts/packages/ts-builders/src/Export.tsnew file mode 100644index 000000000..f32b5a4c9--- /dev/null+++ b/ts/packages/ts-builders/src/Export.ts@@ -0,0 +1,25 @@+import type { AnyDeclarationBuilder } from './AnyDeclarationBuilder';+import type { BasicBuilder } from './BasicBuilder';+import { DocComment } from './DocComment';+import { Writer } from './Writer';++export class Export<Decl extends AnyDeclarationBuilder> implements BasicBuilder {+ private docComment?: DocComment;+ constructor(public readonly declaration: Decl) {}++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }+ writer.write('export ').write(this.declaration);+ }+}++export function moduleExport<Decl extends AnyDeclarationBuilder>(declaration: Decl): Export<Decl> {+ return new Export(declaration);+}diff --git a/ts/packages/ts-builders/src/ExportFrom.test.ts b/ts/packages/ts-builders/src/ExportFrom.test.tsnew file mode 100644index 000000000..ab2da49d4--- /dev/null+++ b/ts/packages/ts-builders/src/ExportFrom.test.ts@@ -0,0 +1,37 @@+import { expect, test } from 'vitest';++import { moduleExportFrom, namedExport } from './ExportFrom';+import { stringify } from './stringify';++test('module name only', () => {+ expect(stringify(moduleExportFrom('someModule'))).toMatchInlineSnapshot(+ `"export * from "someModule""`+ );+});++test('namespace', () => {+ const exportDecl = moduleExportFrom('myModule').asNamespace('ns');+ expect(stringify(exportDecl)).toMatchInlineSnapshot(`"export * as ns from 'myModule'"`);+});++test('named', () => {+ const exportDecl = moduleExportFrom('myModule').named('func');+ expect(stringify(exportDecl)).toMatchInlineSnapshot(`"export { func } from "myModule""`);+});++test('named with alias', () => {+ const exportDecl = moduleExportFrom('myModule').named(namedExport('func').as('myFunc'));+ expect(stringify(exportDecl)).toMatchInlineSnapshot(+ `"export { func as myFunc } from "myModule""`+ );+});++test('multiple named', () => {+ const exportDecl = moduleExportFrom('myModule')+ .named('func1')+ .named('func2')+ .named(namedExport('func3').as('aliasedFunc3'));+ expect(stringify(exportDecl)).toMatchInlineSnapshot(+ `"export { func1, func2, func3 as aliasedFunc3 } from "myModule""`+ );+});diff --git a/ts/packages/ts-builders/src/ExportFrom.ts b/ts/packages/ts-builders/src/ExportFrom.tsnew file mode 100644index 000000000..285ff84da--- /dev/null+++ b/ts/packages/ts-builders/src/ExportFrom.ts@@ -0,0 +1,89 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';++export type ExportFrom = NamespaceExport | BindingsExport | ExportAllFrom;++export class NamespaceExport implements BasicBuilder {+ constructor(+ private from: string,+ private namespace: string+ ) {}++ write(writer: Writer<undefined>): void {+ writer.write(`export * as ${this.namespace} from '${this.from}'`);+ }+}++export class BindingsExport implements BasicBuilder {+ private namedExports: NamedExport[] = [];+ constructor(private from: string) {}++ named(namedExport: string | NamedExport) {+ if (typeof namedExport === 'string') {+ namedExport = new NamedExport(namedExport);+ }+ this.namedExports.push(namedExport);+ return this;+ }++ write(writer: Writer<undefined>): void {+ writer+ .write('export ')+ .write('{ ')+ .writeJoined(', ', this.namedExports)+ .write(' }')++ .write(` from "${this.from}"`);+ }+}++export class NamedExport implements BasicBuilder {+ private alias: string | undefined;+ private type = false;++ constructor(readonly name: string) {}++ as(alias: string) {+ this.alias = alias;+ return this;+ }++ typeOnly(): this {+ this.type = true;+ return this;+ }++ write(writer: Writer): void {+ if (this.type) {+ writer.write('type ');+ }+ writer.write(this.name);+ if (this.alias) {+ writer.write(' as ').write(this.alias);+ }+ }+}++export class ExportAllFrom implements BasicBuilder {+ constructor(private from: string) {}++ asNamespace(namespace: string) {+ return new NamespaceExport(this.from, namespace);+ }++ named(binding: string | NamedExport) {+ return new BindingsExport(this.from).named(binding);+ }++ write(writer: Writer): void {+ writer.write(`export * from "${this.from}"`);+ }+}++export function moduleExportFrom(from: string) {+ return new ExportAllFrom(from);+}++export function namedExport(name: string) {+ return new NamedExport(name);+}diff --git a/ts/packages/ts-builders/src/File.ts b/ts/packages/ts-builders/src/File.tsnew file mode 100644index 000000000..6c5659229--- /dev/null+++ b/ts/packages/ts-builders/src/File.ts@@ -0,0 +1,40 @@+import type { AnyDeclarationBuilder } from './AnyDeclarationBuilder';+import type { BasicBuilder } from './BasicBuilder';+import { Export } from './Export';+import type { ExportFrom } from './ExportFrom';+import type { Import } from './Import';+import { Writer } from './Writer';++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type FileItem = AnyDeclarationBuilder | Export<any> | ExportFrom;+export class File implements BasicBuilder {+ private imports: Import[] = [];+ private declarations: FileItem[] = [];++ addImport(moduleImport: Import) {+ this.imports.push(moduleImport);+ return this;+ }+ add(declaration: FileItem) {+ this.declarations.push(declaration);+ }++ write(writer: Writer<undefined>): void {+ for (const moduleImport of this.imports) {+ writer.writeLine(moduleImport);+ }+ if (this.imports.length > 0) {+ writer.newLine();+ }+ for (const [i, declaration] of this.declarations.entries()) {+ writer.writeLine(declaration);+ if (i < this.declarations.length - 1) {+ writer.newLine();+ }+ }+ }+}++export function file(): File {+ return new File();+}diff --git a/ts/packages/ts-builders/src/FunctionCall.ts b/ts/packages/ts-builders/src/FunctionCall.tsnew file mode 100644index 000000000..798f9d32d--- /dev/null+++ b/ts/packages/ts-builders/src/FunctionCall.ts@@ -0,0 +1,26 @@+import { ValueBuilder } from './ValueBuilder';+import { Writer } from './Writer';++export class FunctionCall extends ValueBuilder {+ #name: string;+ #args: ValueBuilder[];++ constructor(name: string, args: ValueBuilder[]) {+ super();+ this.#name = name;+ this.#args = args;+ }++ addArgument(arg: ValueBuilder): this {+ this.#args.push(arg);+ return this;+ }++ override write(writer: Writer): void {+ writer.write(this.#name).write('(').writeJoined(', ', this.#args).write(')');+ }+}++export function functionCall(name: string, args: ValueBuilder[] = []): FunctionCall {+ return new FunctionCall(name, args);+}diff --git a/ts/packages/ts-builders/src/FunctionType.test.ts b/ts/packages/ts-builders/src/FunctionType.test.tsnew file mode 100644index 000000000..04bc47e07--- /dev/null+++ b/ts/packages/ts-builders/src/FunctionType.test.ts@@ -0,0 +1,43 @@+import { expect, test } from 'vitest';++import { functionType } from './FunctionType';+import { genericParameter } from './GenericParameter';+import { namedType } from './NamedType';+import { parameter } from './Parameter';+import { stringify } from './stringify';++const A = namedType('A');+const B = namedType('B');++test('basic', () => {+ expect(stringify(functionType())).toMatchInlineSnapshot(`"() => void"`);+});++test('with return type', () => {+ const func = functionType().setReturnType(A);+ expect(stringify(func)).toMatchInlineSnapshot(`"() => A"`);+});++test('with parameter', () => {+ const func = functionType().addParameter(parameter('param', A));+ expect(stringify(func)).toMatchInlineSnapshot(`"(param: A) => void"`);+});++test('with multiple parameters', () => {+ const func = functionType()+ .addParameter(parameter('param1', A))+ .addParameter(parameter('param2', B));+ expect(stringify(func)).toMatchInlineSnapshot(`"(param1: A, param2: B) => void"`);+});++test('with generic parameter', () => {+ const func = functionType().addGenericParameter(genericParameter('T'));+ expect(stringify(func)).toMatchInlineSnapshot(`"<T>() => void"`);+});++test('with multiple generic parameters', () => {+ const func = functionType()+ .addGenericParameter(genericParameter('T'))+ .addGenericParameter(genericParameter('U'));+ expect(stringify(func)).toMatchInlineSnapshot(`"<T, U>() => void"`);+});diff --git a/ts/packages/ts-builders/src/FunctionType.ts b/ts/packages/ts-builders/src/FunctionType.tsnew file mode 100644index 000000000..920224dc0--- /dev/null+++ b/ts/packages/ts-builders/src/FunctionType.ts@@ -0,0 +1,40 @@+import { GenericParameter } from './GenericParameter';+import { Parameter } from './Parameter';+import { voidType } from './PrimitiveType';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class FunctionType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.FunctionType;+ private returnType: TypeBuilder = voidType;+ private parameters: Parameter[] = [];+ private genericParameters: GenericParameter[] = [];++ setReturnType(returnType: TypeBuilder): this {+ this.returnType = returnType;+ return this;+ }++ addParameter(param: Parameter): this {+ this.parameters.push(param);+ return this;+ }++ addGenericParameter(param: GenericParameter): this {+ this.genericParameters.push(param);+ return this;+ }++ write(writer: Writer): void {+ if (this.genericParameters.length > 0) {+ writer.write('<').writeJoined(', ', this.genericParameters).write('>');+ }+ writer.write('(').writeJoined(', ', this.parameters).write(') => ');+ this.returnType.writeInContext(writer, TypeContext.FunctionReturn);+ }+}++export function functionType(): FunctionType {+ return new FunctionType();+}diff --git a/ts/packages/ts-builders/src/GenericParameter.test.ts b/ts/packages/ts-builders/src/GenericParameter.test.tsnew file mode 100644index 000000000..41b1f020b--- /dev/null+++ b/ts/packages/ts-builders/src/GenericParameter.test.ts@@ -0,0 +1,26 @@+import { expect, test } from 'vitest';++import { genericParameter } from './GenericParameter';+import { namedType } from './NamedType';+import { stringify } from './stringify';++const A = namedType('A');+const B = namedType('B');++test('name only', () => {+ expect(stringify(genericParameter('T'))).toMatchInlineSnapshot(`"T"`);+});++test('with extends', () => {+ expect(stringify(genericParameter('T').extends(A))).toMatchInlineSnapshot(`"T extends A"`);+});++test('with default', () => {+ expect(stringify(genericParameter('T').default(B))).toMatchInlineSnapshot(`"T = B"`);+});++test('with extends + default', () => {+ expect(stringify(genericParameter('T').extends(A).default(B))).toMatchInlineSnapshot(+ `"T extends A = B"`+ );+});diff --git a/ts/packages/ts-builders/src/GenericParameter.ts b/ts/packages/ts-builders/src/GenericParameter.tsnew file mode 100644index 000000000..14a6b7a8a--- /dev/null+++ b/ts/packages/ts-builders/src/GenericParameter.ts@@ -0,0 +1,39 @@+import type { BasicBuilder } from './BasicBuilder';+import { NamedType } from './NamedType';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';++export class GenericParameter implements BasicBuilder {+ private extendedType?: TypeBuilder;+ private defaultType?: TypeBuilder;++ constructor(private name: string) {}++ extends(type: TypeBuilder): this {+ this.extendedType = type;+ return this;+ }++ default(type: TypeBuilder): this {+ this.defaultType = type;+ return this;+ }++ toArgument(): NamedType {+ return new NamedType(this.name);+ }++ write(writer: Writer): void {+ writer.write(this.name);+ if (this.extendedType) {+ writer.write(' extends ').write(this.extendedType);+ }+ if (this.defaultType) {+ writer.write(' = ').write(this.defaultType);+ }+ }+}++export function genericParameter(name: string): GenericParameter {+ return new GenericParameter(name);+}diff --git a/ts/packages/ts-builders/src/Import.test.ts b/ts/packages/ts-builders/src/Import.test.tsnew file mode 100644index 000000000..7712d6db0--- /dev/null+++ b/ts/packages/ts-builders/src/Import.test.ts@@ -0,0 +1,47 @@+import { expect, test } from 'vitest';++import { moduleImport, namedImport } from './Import';+import { stringify } from './stringify';++test('module name only', () => {+ expect(stringify(moduleImport('someModule'))).toMatchInlineSnapshot(`"import "someModule""`);+});++test('default', () => {+ const importDecl = moduleImport('myModule').default('mod');+ expect(stringify(importDecl)).toMatchInlineSnapshot(`"import mod from "myModule""`);+});++test('namespace', () => {+ const importDecl = moduleImport('myModule').asNamespace('ns');+ expect(stringify(importDecl)).toMatchInlineSnapshot(`"import * as ns from "myModule""`);+});++test('named', () => {+ const importDecl = moduleImport('myModule').named('func');+ expect(stringify(importDecl)).toMatchInlineSnapshot(`"import { func } from "myModule""`);+});++test('named with alias', () => {+ const importDecl = moduleImport('myModule').named(namedImport('func').as('myFunc'));+ expect(stringify(importDecl)).toMatchInlineSnapshot(+ `"import { func as myFunc } from "myModule""`+ );+});++test('multiple named', () => {+ const importDecl = moduleImport('myModule')+ .named('func1')+ .named('func2')+ .named(namedImport('func3').as('aliasedFunc3'));+ expect(stringify(importDecl)).toMatchInlineSnapshot(+ `"import { func1, func2, func3 as aliasedFunc3 } from "myModule""`+ );+});++test('default and named', () => {+ const importDecl = moduleImport('myModule').default('mod').named('func1').named('func2');+ expect(stringify(importDecl)).toMatchInlineSnapshot(+ `"import mod, { func1, func2 } from "myModule""`+ );+});diff --git a/ts/packages/ts-builders/src/Import.ts b/ts/packages/ts-builders/src/Import.tsnew file mode 100644index 000000000..3851d5d97--- /dev/null+++ b/ts/packages/ts-builders/src/Import.ts@@ -0,0 +1,120 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';++export type Import = NamespaceImport | BindingsImport | ModuleImport;++export class NamespaceImport implements BasicBuilder {+ private type = false;++ constructor(+ readonly alias: string,+ readonly from: string+ ) {}++ typeOnly() {+ this.type = true;+ return this;+ }++ write(writer: Writer<undefined>): void {+ writer.write('import ');+ if (this.type) {+ writer.write('type ');+ }+ writer.write('* as ').write(this.alias).write(` from "${this.from}"`);+ }+}++export class BindingsImport implements BasicBuilder {+ private defaultImport: string | undefined;+ private namedImports: NamedImport[] = [];+ constructor(readonly from: string) {}++ default(name: string) {+ this.defaultImport = name;+ return this;+ }++ named(namedImport: string | NamedImport) {+ if (typeof namedImport === 'string') {+ namedImport = new NamedImport(namedImport);+ }+ this.namedImports.push(namedImport);+ return this;+ }++ write(writer: Writer): void {+ writer.write('import ');+ if (this.defaultImport) {+ writer.write(this.defaultImport);+ if (this.hasNamedImports()) {+ writer.write(', ');+ }+ }++ if (this.hasNamedImports()) {+ writer.write('{ ').writeJoined(', ', this.namedImports).write(' }');+ }++ writer.write(` from "${this.from}"`);+ }++ private hasNamedImports() {+ return this.namedImports.length > 0;+ }+}++export class NamedImport implements BasicBuilder {+ private alias: string | undefined;+ private type = false;++ constructor(readonly name: string) {}++ as(alias: string) {+ this.alias = alias;+ return this;+ }++ typeOnly() {+ this.type = true;+ return this;+ }++ write(writer: Writer): void {+ if (this.type) {+ writer.write('type ');+ }+ writer.write(this.name);+ if (this.alias) {+ writer.write(' as ').write(this.alias);+ }+ }+}++export class ModuleImport implements BasicBuilder {+ constructor(readonly from: string) {}++ asNamespace(alias: string): NamespaceImport {+ return new NamespaceImport(alias, this.from);+ }++ default(alias: string): BindingsImport {+ return new BindingsImport(this.from).default(alias);+ }++ named(namedImport: string | NamedImport) {+ return new BindingsImport(this.from).named(namedImport);+ }++ write(writer: Writer): void {+ writer.write('import ').write(`"${this.from}"`);+ }+}++export function moduleImport(from: string) {+ return new ModuleImport(from);+}++export function namedImport(name: string) {+ return new NamedImport(name);+}diff --git a/ts/packages/ts-builders/src/Interface.test.ts b/ts/packages/ts-builders/src/Interface.test.tsnew file mode 100644index 000000000..c4c15cace--- /dev/null+++ b/ts/packages/ts-builders/src/Interface.test.ts@@ -0,0 +1,70 @@+import { expect, test } from 'vitest';++import { genericParameter } from './GenericParameter';+import { interfaceDeclaration } from './Interface';+import { method } from './Method';+import { namedType } from './NamedType';+import { property } from './Property';+import { stringify } from './stringify';++const A = namedType('A');++test('empty', () => {+ const obj = interfaceDeclaration('MyInterface');+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface MyInterface {}+ "+ `);+});++test('with property', () => {+ const obj = interfaceDeclaration('SomeInterface').add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface SomeInterface {+ foo: A+ }"+ `);+});++test('with method', () => {+ const obj = interfaceDeclaration('MyInterface').add(method('doThing'));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface MyInterface {+ doThing(): void+ }"+ `);+});++test('with generic parameter', () => {+ const obj = interfaceDeclaration('SomeInterface')+ .addGenericParameter(genericParameter('T').extends(namedType('U')))+ .add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface SomeInterface<T extends U> {+ foo: A+ }"+ `);+});++test('extending the type', () => {+ const obj = interfaceDeclaration('SomeInterface')+ .extends(namedType('Foo'))+ .add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface SomeInterface extends Foo {+ foo: A+ }"+ `);+});++test('extending multiple types', () => {+ const obj = interfaceDeclaration('SomeInterface')+ .extends(namedType('Foo'))+ .extends(namedType('Bar'))+ .add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "interface SomeInterface extends Foo, Bar {+ foo: A+ }"+ `);+});diff --git a/ts/packages/ts-builders/src/Interface.ts b/ts/packages/ts-builders/src/Interface.tsnew file mode 100644index 000000000..5d970cc99--- /dev/null+++ b/ts/packages/ts-builders/src/Interface.ts@@ -0,0 +1,72 @@+import { GenericParameter } from './GenericParameter';+import { Method } from './Method';+import { NamedType } from './NamedType';+import { Property } from './Property';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++type InterfaceItem = Method | Property;++export class InterfaceDeclaration extends TypeBuilder {+ needsParenthesisWhenIndexed = true;+ readonly precedence = OperatorPrecedence.ObjectType;++ private items: InterfaceItem[] = [];+ private genericParameters: GenericParameter[] = [];+ private extendedTypes: NamedType[] = [];++ constructor(readonly name: string) {+ super();+ }++ add(item: InterfaceItem): this {+ this.items.push(item);+ return this;+ }++ addMultiple(items: InterfaceItem[]): this {+ for (const item of items) {+ this.add(item);+ }+ return this;+ }++ addGenericParameter(param: GenericParameter) {+ this.genericParameters.push(param);+ return this;+ }++ extends(type: NamedType) {+ this.extendedTypes.push(type);+ return this;+ }++ write(writer: Writer): void {+ writer.write('interface ').write(this.name);+ if (this.genericParameters.length > 0) {+ writer.write('<').writeJoined(', ', this.genericParameters).write('>');+ }++ if (this.extendedTypes.length > 0) {+ writer.write(' extends ').writeJoined(', ', this.extendedTypes);+ }+ if (this.items.length === 0) {+ writer.writeLine(' {}');+ return;+ }++ writer+ .writeLine(' {')+ .withIndent(() => {+ for (const item of this.items) {+ writer.writeLine(item);+ }+ })+ .write('}');+ }+}++export function interfaceDeclaration(name: string) {+ return new InterfaceDeclaration(name);+}diff --git a/ts/packages/ts-builders/src/KeyType.test.ts b/ts/packages/ts-builders/src/KeyType.test.tsnew file mode 100644index 000000000..f272879dd--- /dev/null+++ b/ts/packages/ts-builders/src/KeyType.test.ts@@ -0,0 +1,36 @@+import { expect, test } from 'vitest';++import { array } from './ArrayType';+import { functionType } from './FunctionType';+import { keyType } from './KeyType';+import { namedType } from './NamedType';+import { objectType } from './ObjectType';+import { stringify } from './stringify';+import { unionType } from './UnionType';++const A = namedType('A');+const B = namedType('B');+const C = namedType('C');++test('simple only', () => {+ expect(stringify(keyType(A, 'foo'))).toMatchInlineSnapshot(`"A["foo"]"`);+});++test('with object type', () => {+ expect(stringify(keyType(objectType(), 'toString'))).toMatchInlineSnapshot(`"({})["toString"]"`);+});++test('with array type', () => {+ expect(stringify(keyType(array(A), 'length'))).toMatchInlineSnapshot(`"A[]["length"]"`);+});++test('with function type', () => {+ expect(stringify(keyType(functionType(), 'length'))).toMatchInlineSnapshot(+ `"(() => void)["length"]"`+ );+});++test('with union type', () => {+ const union = unionType(A).addVariant(B).addVariant(C);+ expect(stringify(keyType(union, 'foo'))).toMatchInlineSnapshot(`"(A | B | C)["foo"]"`);+});diff --git a/ts/packages/ts-builders/src/KeyType.ts b/ts/packages/ts-builders/src/KeyType.tsnew file mode 100644index 000000000..3cce483e7--- /dev/null+++ b/ts/packages/ts-builders/src/KeyType.ts@@ -0,0 +1,27 @@+import { TypeBuilder } from './TypeBuilder';+import { NamedType } from './NamedType';+import type { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class KeyType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.IndexAccess;++ constructor(+ public baseType: TypeBuilder,+ public key: string | NamedType+ ) {+ super();+ }++ write(writer: Writer): void {+ this.baseType.writeInContext(writer, TypeContext.IndexAccess);++ const keyIndexed = this.key instanceof NamedType ? `${this.key.name}` : `"${this.key}"`;++ writer.write('[').write(keyIndexed).write(']');+ }+}++export function keyType(baseType: TypeBuilder, key: string | NamedType) {+ return new KeyType(baseType, key);+}diff --git a/ts/packages/ts-builders/src/KeyofType.test.ts b/ts/packages/ts-builders/src/KeyofType.test.tsnew file mode 100644index 000000000..77d73866b--- /dev/null+++ b/ts/packages/ts-builders/src/KeyofType.test.ts@@ -0,0 +1,34 @@+import { expect, test } from 'vitest';++import { array } from './ArrayType';+import { functionType } from './FunctionType';+import { keyOfType } from './KeyofType';+import { namedType } from './NamedType';+import { objectType } from './ObjectType';+import { stringify } from './stringify';+import { unionType } from './UnionType';++const A = namedType('A');+const B = namedType('B');+const C = namedType('C');++test('simple only', () => {+ expect(stringify(keyOfType(A))).toMatchInlineSnapshot(`"keyof A"`);+});++test('with object type', () => {+ expect(stringify(keyOfType(objectType()))).toMatchInlineSnapshot(`"keyof {}"`);+});++test('with array type', () => {+ expect(stringify(keyOfType(array(A)))).toMatchInlineSnapshot(`"keyof A[]"`);+});++test('with function type', () => {+ expect(stringify(keyOfType(functionType()))).toMatchInlineSnapshot(`"keyof (() => void)"`);+});++test('with union type', () => {+ const union = unionType(A).addVariant(B).addVariant(C);+ expect(stringify(keyOfType(union))).toMatchInlineSnapshot(`"keyof (A | B | C)"`);+});diff --git a/ts/packages/ts-builders/src/KeyofType.ts b/ts/packages/ts-builders/src/KeyofType.tsnew file mode 100644index 000000000..867c844a1--- /dev/null+++ b/ts/packages/ts-builders/src/KeyofType.ts@@ -0,0 +1,20 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class KeyofType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.KeyofType;++ constructor(public baseType: TypeBuilder) {+ super();+ }++ write(writer: Writer): void {+ writer.write(`keyof `);+ this.baseType.writeInContext(writer, TypeContext.KeyofOperand);+ }+}++export function keyOfType(baseType: TypeBuilder): KeyofType {+ return new KeyofType(baseType);+}diff --git a/ts/packages/ts-builders/src/Method.test.ts b/ts/packages/ts-builders/src/Method.test.tsnew file mode 100644index 000000000..f9b01c90d--- /dev/null+++ b/ts/packages/ts-builders/src/Method.test.ts@@ -0,0 +1,53 @@+import { expect, test } from 'vitest';++import { docComment } from './DocComment';+import { genericParameter } from './GenericParameter';+import { method } from './Method';+import { namedType } from './NamedType';+import { parameter } from './Parameter';+import { stringify } from './stringify';++const A = namedType('A');+const B = namedType('B');++test('name only', () => {+ const m = method('doThings');+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings(): void"`);+});++test('with return type', () => {+ const m = method('doThings').setReturnType(A);+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings(): A"`);+});++test('with doc comment', () => {+ const m = method('doThings').setDocComment(docComment('Does things'));+ expect(stringify(m)).toMatchInlineSnapshot(`+ "/**+ * Does things+ */+ doThings(): void"+ `);+});++test('with parameter', () => {+ const m = method('doThings').addParameter(parameter('foo', A));+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings(foo: A): void"`);+});++test('with multiple parameters', () => {+ const m = method('doThings').addParameter(parameter('foo', A)).addParameter(parameter('foo', B));+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings(foo: A, foo: B): void"`);+});++test('with generic parameter', () => {+ const m = method('doThings').addGenericParameter(genericParameter('T'));+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings<T>(): void"`);+});++test('with multiple generic parameters', () => {+ const m = method('doThings')+ .addGenericParameter(genericParameter('T'))+ .addGenericParameter(genericParameter('U'));+ expect(stringify(m)).toMatchInlineSnapshot(`"doThings<T, U>(): void"`);+});diff --git a/ts/packages/ts-builders/src/Method.ts b/ts/packages/ts-builders/src/Method.tsnew file mode 100644index 000000000..67bf4f827--- /dev/null+++ b/ts/packages/ts-builders/src/Method.ts@@ -0,0 +1,60 @@+import type { BasicBuilder } from './BasicBuilder';+import { DocComment } from './DocComment';+import { GenericParameter } from './GenericParameter';+import { Parameter } from './Parameter';+import { voidType } from './PrimitiveType';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';++export class Method implements BasicBuilder {+ private docComment?: DocComment;+ private returnType: TypeBuilder = voidType;+ private parameters: Parameter[] = [];+ private genericParameters: GenericParameter[] = [];+ constructor(private name: string) {}++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ setReturnType(returnType: TypeBuilder): this {+ this.returnType = returnType;+ return this;+ }++ addParameter(param: Parameter): this {+ this.parameters.push(param);+ return this;+ }++ addGenericParameter(param: GenericParameter): this {+ this.genericParameters.push(param);+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }++ writer.write(this.name);+ if (this.genericParameters.length > 0) {+ writer.write('<').writeJoined(', ', this.genericParameters).write('>');+ }++ writer.write('(');+ if (this.parameters.length > 0) {+ writer.writeJoined(', ', this.parameters);+ }+ writer.write(')');++ if (this.name !== 'constructor') {+ writer.write(': ').write(this.returnType);+ }+ }+}++export function method(name: string): Method {+ return new Method(name);+}diff --git a/ts/packages/ts-builders/src/NamedType.test.ts b/ts/packages/ts-builders/src/NamedType.test.tsnew file mode 100644index 000000000..f7431d379--- /dev/null+++ b/ts/packages/ts-builders/src/NamedType.test.ts@@ -0,0 +1,22 @@+import { expect, test } from 'vitest';++import { namedType } from './NamedType';+import { stringify } from './stringify';++test('name only', () => {+ expect(stringify(namedType('MyType'))).toMatchInlineSnapshot(`"MyType"`);+});++test('with generic argument', () => {+ expect(stringify(namedType('MyType').addGenericArgument(namedType('Foo')))).toMatchInlineSnapshot(+ `"MyType<Foo>"`+ );+});++test('with multiple generic arguments', () => {+ expect(+ stringify(+ namedType('MyType').addGenericArgument(namedType('Foo')).addGenericArgument(namedType('Bar'))+ )+ ).toMatchInlineSnapshot(`"MyType<Foo, Bar>"`);+});diff --git a/ts/packages/ts-builders/src/NamedType.ts b/ts/packages/ts-builders/src/NamedType.tsnew file mode 100644index 000000000..031b576bd--- /dev/null+++ b/ts/packages/ts-builders/src/NamedType.ts@@ -0,0 +1,28 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++export class NamedType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.Atomic;+ readonly genericArguments: TypeBuilder[] = [];++ constructor(readonly name: string) {+ super();+ }++ addGenericArgument(type: TypeBuilder): this {+ this.genericArguments.push(type);+ return this;+ }++ write(writer: Writer): void {+ writer.write(this.name);+ if (this.genericArguments.length > 0) {+ writer.write('<').writeJoined(', ', this.genericArguments).write('>');+ }+ }+}++export function namedType(name: string): NamedType {+ return new NamedType(name);+}diff --git a/ts/packages/ts-builders/src/NamedValue.ts b/ts/packages/ts-builders/src/NamedValue.tsnew file mode 100644index 000000000..b4f702385--- /dev/null+++ b/ts/packages/ts-builders/src/NamedValue.ts@@ -0,0 +1,19 @@+import { ValueBuilder } from './ValueBuilder';+import { Writer } from './Writer';++export class NamedValue extends ValueBuilder {+ #name: string;++ constructor(name: string) {+ super();+ this.#name = name;+ }++ override write(writer: Writer): void {+ writer.write(this.#name);+ }+}++export function namedValue(name: string): NamedValue {+ return new NamedValue(name);+}diff --git a/ts/packages/ts-builders/src/NamespaceDeclaration.ts b/ts/packages/ts-builders/src/NamespaceDeclaration.tsnew file mode 100644index 000000000..5b2fa15bf--- /dev/null+++ b/ts/packages/ts-builders/src/NamespaceDeclaration.ts@@ -0,0 +1,29 @@+import type { AnyDeclarationBuilder } from './AnyDeclarationBuilder';+import type { BasicBuilder } from './BasicBuilder';+import { Export } from './Export';+import { Writer } from './Writer';++export type NamespaceItem = AnyDeclarationBuilder | Export<AnyDeclarationBuilder>;+export class NamespaceDeclaration implements BasicBuilder {+ private items: NamespaceItem[] = [];+ constructor(readonly name: string) {}++ add(declaration: NamespaceItem) {+ this.items.push(declaration);+ }++ write(writer: Writer<undefined>): void {+ writer+ .writeLine(`namespace ${this.name} {`)+ .withIndent(() => {+ for (const item of this.items) {+ writer.writeLine(item);+ }+ })+ .write('}');+ }+}++export function namespace(name: string): NamespaceDeclaration {+ return new NamespaceDeclaration(name);+}diff --git a/ts/packages/ts-builders/src/ObjectType.test.ts b/ts/packages/ts-builders/src/ObjectType.test.tsnew file mode 100644index 000000000..d8c77ae77--- /dev/null+++ b/ts/packages/ts-builders/src/ObjectType.test.ts@@ -0,0 +1,37 @@+import { expect, test } from 'vitest';++import { method } from './Method';+import { namedType } from './NamedType';+import { objectType } from './ObjectType';+import { property } from './Property';+import { stringify } from './stringify';++const A = namedType('A');++test('empty', () => {+ const obj = objectType();+ expect(stringify(obj)).toMatchInlineSnapshot(`"{}"`);+});++test('with property', () => {+ const obj = objectType().add(property('foo', A));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "{+ foo: A+ }"+ `);+});++test('with method', () => {+ const obj = objectType().add(method('doThing'));+ expect(stringify(obj)).toMatchInlineSnapshot(`+ "{+ doThing(): void+ }"+ `);+});++test('inline formatting', () => {+ const obj = objectType().add(property('foo', A)).formatInline();+ expect(stringify(obj)).toMatchInlineSnapshot(`"{ foo: A }"`);+});diff --git a/ts/packages/ts-builders/src/ObjectType.ts b/ts/packages/ts-builders/src/ObjectType.tsnew file mode 100644index 000000000..53cb80e80--- /dev/null+++ b/ts/packages/ts-builders/src/ObjectType.ts@@ -0,0 +1,60 @@+import { Method } from './Method';+import { Property } from './Property';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++type ObjectTypeItem = Method | Property;++export class ObjectType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.ObjectType;++ private items: ObjectTypeItem[] = [];+ private inline = false;++ add(item: ObjectTypeItem): this {+ this.items.push(item);+ return this;+ }++ addMultiple(items: ObjectTypeItem[]): this {+ for (const item of items) {+ this.add(item);+ }+ return this;+ }++ formatInline() {+ this.inline = true;+ return this;+ }++ write(writer: Writer): void {+ if (this.items.length === 0) {+ writer.write('{}');+ } else if (this.inline) {+ this.writeInline(writer);+ } else {+ this.writeMultiline(writer);+ }+ }++ private writeMultiline(writer: Writer) {+ writer+ .writeLine('{')+ .withIndent(() => {+ for (const item of this.items) {+ writer.writeLine(item);+ }+ })+ .write('}');+ }++ private writeInline(writer: Writer) {+ writer.write('{ ').writeJoined(', ', this.items).write(' }');+ }+}++export function objectType() {+ return new ObjectType();+}diff --git a/ts/packages/ts-builders/src/ObjectValue.ts b/ts/packages/ts-builders/src/ObjectValue.tsnew file mode 100644index 000000000..e33eed8dc--- /dev/null+++ b/ts/packages/ts-builders/src/ObjectValue.ts@@ -0,0 +1,60 @@+import { ValueBuilder } from './ValueBuilder';+import { PropertyValue } from './PropertyValue';+import type { Writer } from './Writer';++type ObjectTypeItem = PropertyValue;++export class ObjectValue extends ValueBuilder {+ needsParenthesisWhenIndexed = true;++ private items: ObjectTypeItem[] = [];+ private inline = false;++ add(item: ObjectTypeItem): this {+ this.items.push(item);+ return this;+ }++ addMultiple(items: ObjectTypeItem[]): this {+ for (const item of items) {+ this.add(item);+ }+ return this;+ }++ formatInline() {+ this.inline = true;+ return this;+ }++ write(writer: Writer): void {+ if (this.items.length === 0) {+ writer.write('{}');+ } else if (this.inline) {+ this.writeInline(writer);+ } else {+ this.writeMultiline(writer);+ }+ }++ private writeMultiline(writer: Writer) {+ writer+ .writeLine('{')+ .withIndent(() => {+ for (const item of this.items) {+ writer.write(item);+ writer.write(',');+ writer.newLine();+ }+ })+ .write('}');+ }++ private writeInline(writer: Writer) {+ writer.write('{ ').writeJoined(', ', this.items).write(' }');+ }+}++export function objectValue() {+ return new ObjectValue();+}diff --git a/ts/packages/ts-builders/src/OperatorPrecedence.ts b/ts/packages/ts-builders/src/OperatorPrecedence.tsnew file mode 100644index 000000000..b609b77a5--- /dev/null+++ b/ts/packages/ts-builders/src/OperatorPrecedence.ts@@ -0,0 +1,89 @@+/* eslint-disable @typescript-eslint/no-duplicate-enum-values */++/**+ * TypeScript operator precedence levels for automatic parentheses placement.+ * Higher numbers indicate higher precedence (bind more tightly).+ *+ * Based on TypeScript/JavaScript operator precedence:+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence+ */+export enum OperatorPrecedence {+ // Lowest precedence+ Union = 1, // A | B+ Intersection = 2, // A & B+ Conditional = 3, // A extends B ? C : D++ // Typeof types are special cases, see:+ // https://stackoverflow.com/questions/70102722/whats-the-precedence-of-typescript-operators#comment123924051_70102722+ TypeofType = 4, // typeof T++ // Function types+ FunctionType = 4, // () => void++ // Object types (lower precedence than arrays so they need parentheses in more contexts)+ ObjectType = 5, // { a: string }++ // Array and tuple types+ ArrayType = 6, // T[]+ TupleType = 6, // [A, B, C]++ // Indexing and property access+ IndexAccess = 7, // T[K]++ // Unary operators+ KeyofType = 8, // keyof T++ // Highest precedence (atomic types, least likely to need parentheses)+ Atomic = 10, // string, number, boolean, literal types, named types+}++/**+ * Context in which a type is being written, used to determine if parentheses are needed+ */+export enum TypeContext {+ Root = 'root', // Top-level, no context+ UnionMember = 'union_member', // Inside a union type+ IntersectionMember = 'intersection_member', // Inside an intersection type+ ArrayElement = 'array_element', // T in T[]+ TupleElement = 'tuple_element', // T in [T, ...]+ IndexAccess = 'index_access', // T in T[K] or K in T[K]+ KeyofOperand = 'keyof_operand', // T in keyof T+ TypeofOperand = 'typeof_operand', // T in typeof T+ FunctionReturn = 'function_return', // T in () => T+ FunctionParameter = 'function_parameter', // T in (x: T) => void+ ObjectProperty = 'object_property', // T in { prop: T }+ ConditionalCheck = 'conditional_check', // T in T extends U ? V : W+ ConditionalTrue = 'conditional_true', // V in T extends U ? V : W+ ConditionalFalse = 'conditional_false', // W in T extends U ? V : W+}++/**+ * Maps contexts to the minimum precedence level that doesn't require parentheses+ */+export const CONTEXT_PRECEDENCE: Record<TypeContext, OperatorPrecedence> = {+ [TypeContext.Root]: OperatorPrecedence.Union,+ [TypeContext.UnionMember]: OperatorPrecedence.ArrayType, // Functions (4) < ArrayType (6) = true, parentheses added+ [TypeContext.IntersectionMember]: OperatorPrecedence.Conditional,+ [TypeContext.ArrayElement]: OperatorPrecedence.Atomic, // Objects (5) < Atomic (10) = true, parentheses added+ [TypeContext.TupleElement]: OperatorPrecedence.ArrayType,+ [TypeContext.IndexAccess]: OperatorPrecedence.ArrayType, // Objects (5) < ArrayType (6) = true, Arrays (6) < ArrayType (6) = false+ [TypeContext.KeyofOperand]: OperatorPrecedence.ObjectType, // Functions (4) < ObjectType (5) = true, Unions (1) < ObjectType (5) = true, Objects (5) < ObjectType (5) = false, Arrays (6) < ObjectType (5) = false+ [TypeContext.FunctionReturn]: OperatorPrecedence.FunctionType,+ [TypeContext.TypeofOperand]: OperatorPrecedence.TypeofType,+ [TypeContext.FunctionParameter]: OperatorPrecedence.FunctionType,+ [TypeContext.ObjectProperty]: OperatorPrecedence.ObjectType,+ [TypeContext.ConditionalCheck]: OperatorPrecedence.Conditional,+ [TypeContext.ConditionalTrue]: OperatorPrecedence.Conditional,+ [TypeContext.ConditionalFalse]: OperatorPrecedence.Conditional,+};++/**+ * Determines if parentheses are needed when writing a type in a given context+ */+export function needsParentheses(+ typePrecedence: OperatorPrecedence,+ context: TypeContext+): boolean {+ const contextPrecedence = CONTEXT_PRECEDENCE[context];+ return typePrecedence < contextPrecedence;+}diff --git a/ts/packages/ts-builders/src/Parameter.test.ts b/ts/packages/ts-builders/src/Parameter.test.tsnew file mode 100644index 000000000..db5cbef0b--- /dev/null+++ b/ts/packages/ts-builders/src/Parameter.test.ts@@ -0,0 +1,19 @@+import { expect, test } from 'vitest';++import { namedType } from './NamedType';+import { parameter } from './Parameter';+import { stringify } from './stringify';++const A = namedType('A');++test('name and type', () => {+ const param = parameter('foo', A);++ expect(stringify(param)).toMatchInlineSnapshot(`"foo: A"`);+});++test('optional', () => {+ const param = parameter('foo', A).optional();++ expect(stringify(param)).toMatchInlineSnapshot(`"foo?: A"`);+});diff --git a/ts/packages/ts-builders/src/Parameter.ts b/ts/packages/ts-builders/src/Parameter.tsnew file mode 100644index 000000000..3145e2387--- /dev/null+++ b/ts/packages/ts-builders/src/Parameter.ts@@ -0,0 +1,28 @@+import type { BasicBuilder } from './BasicBuilder';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';++export class Parameter implements BasicBuilder {+ private isOptional = false;+ constructor(+ private name: string,+ private type: TypeBuilder+ ) {}++ optional(): this {+ this.isOptional = true;+ return this;+ }++ write(writer: Writer): void {+ writer.write(this.name);+ if (this.isOptional) {+ writer.write('?');+ }+ writer.write(': ').write(this.type);+ }+}++export function parameter(name: string, type: TypeBuilder) {+ return new Parameter(name, type);+}diff --git a/ts/packages/ts-builders/src/PrimitiveType.ts b/ts/packages/ts-builders/src/PrimitiveType.tsnew file mode 100644index 000000000..131ae88c2--- /dev/null+++ b/ts/packages/ts-builders/src/PrimitiveType.ts@@ -0,0 +1,27 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++export class PrimitiveType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.Atomic;++ constructor(private name: string) {+ super();+ }++ write(writer: Writer): void {+ writer.write(this.name);+ }+}++export const stringType = new PrimitiveType('string');+export const numberType = new PrimitiveType('number');+export const booleanType = new PrimitiveType('boolean');+export const nullType = new PrimitiveType('null');+export const undefinedType = new PrimitiveType('undefined');+export const bigintType = new PrimitiveType('bigint');+export const unknownType = new PrimitiveType('unknown');+export const anyType = new PrimitiveType('any');+export const voidType = new PrimitiveType('void');+export const thisType = new PrimitiveType('this');+export const neverType = new PrimitiveType('never');diff --git a/ts/packages/ts-builders/src/Property.test.ts b/ts/packages/ts-builders/src/Property.test.tsnew file mode 100644index 000000000..9741d9335--- /dev/null+++ b/ts/packages/ts-builders/src/Property.test.ts@@ -0,0 +1,50 @@+import { expect, test } from 'vitest';++import { docComment } from './DocComment';+import { namedType } from './NamedType';+import { property } from './Property';+import { stringify } from './stringify';+import { toStringTag } from './WellKnownSymbol';++const A = namedType('A');++test('name and type', () => {+ const prop = property('foo', A);++ expect(stringify(prop)).toMatchInlineSnapshot(`"foo: A"`);+});++test('invalid identifier', () => {+ const prop = property('this is not a valid JS identifier', A);++ expect(stringify(prop)).toMatchInlineSnapshot(`"["this is not a valid JS identifier"]: A"`);+});++test('well-known symbol', () => {+ const prop = property(toStringTag, A);++ expect(stringify(prop)).toMatchInlineSnapshot(`"[Symbol.toStringTag]: A"`);+});++test('optional', () => {+ const prop = property('foo', A).optional();++ expect(stringify(prop)).toMatchInlineSnapshot(`"foo?: A"`);+});++test('readonly', () => {+ const prop = property('foo', A).readonly();++ expect(stringify(prop)).toMatchInlineSnapshot(`"readonly foo: A"`);+});++test('with doc comment', () => {+ const prop = property('foo', A).setDocComment(docComment('This is foo'));++ expect(stringify(prop)).toMatchInlineSnapshot(`+ "/**+ * This is foo+ */+ foo: A"+ `);+});diff --git a/ts/packages/ts-builders/src/Property.ts b/ts/packages/ts-builders/src/Property.tsnew file mode 100644index 000000000..e123f0e72--- /dev/null+++ b/ts/packages/ts-builders/src/Property.ts@@ -0,0 +1,60 @@+import type { BasicBuilder } from './BasicBuilder';+import { DocComment } from './DocComment';+import { isValidJsIdentifier } from './isValidJsIdentifier';+import { TypeBuilder } from './TypeBuilder';+import { WellKnownSymbol } from './WellKnownSymbol';+import { Writer } from './Writer';++export class Property implements BasicBuilder {+ private isOptional = false;+ private isReadonly = false;+ private docComment?: DocComment;++ constructor(+ private name: string | WellKnownSymbol,+ private type: TypeBuilder+ ) {}++ optional(): this {+ this.isOptional = true;+ return this;+ }++ readonly(): this {+ this.isReadonly = true;+ return this;+ }++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }+ if (this.isReadonly) {+ writer.write('readonly ');+ }++ if (typeof this.name === 'string') {+ if (isValidJsIdentifier(this.name)) {+ writer.write(this.name);+ } else {+ writer.write('[').write(JSON.stringify(this.name)).write(']');+ }+ } else {+ writer.write('[').write(this.name).write(']');+ }++ if (this.isOptional) {+ writer.write('?');+ }+ writer.write(': ').write(this.type);+ }+}++export function property(name: string | WellKnownSymbol, type: TypeBuilder) {+ return new Property(name, type);+}diff --git a/ts/packages/ts-builders/src/PropertyValue.ts b/ts/packages/ts-builders/src/PropertyValue.tsnew file mode 100644index 000000000..12050fc19--- /dev/null+++ b/ts/packages/ts-builders/src/PropertyValue.ts@@ -0,0 +1,46 @@+import { DocComment } from './DocComment';+import { WellKnownSymbol } from './WellKnownSymbol';+import { ValueBuilder } from './ValueBuilder';+import { Writer } from './Writer';+import type { BasicBuilder } from './BasicBuilder';++export class PropertyValue implements BasicBuilder {+ private isOptional = false;+ private docComment?: DocComment;++ constructor(+ public name: string | WellKnownSymbol,+ public value: ValueBuilder+ ) {}++ optional(): this {+ this.isOptional = true;+ return this;+ }++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }++ if (typeof this.name === 'string') {+ writer.write(this.name);+ } else {+ writer.write('[').write(this.name).write(']');+ }++ if (this.isOptional) {+ writer.write('?');+ }+ writer.write(': ').write(this.value);+ }+}++export function propertyValue(name: string | WellKnownSymbol, value: ValueBuilder) {+ return new PropertyValue(name, value);+}diff --git a/ts/packages/ts-builders/src/QuoteStyle.test.ts b/ts/packages/ts-builders/src/QuoteStyle.test.tsnew file mode 100644index 000000000..64250537b--- /dev/null+++ b/ts/packages/ts-builders/src/QuoteStyle.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect } from 'vitest';+import { QuoteStyle, escapeStringContent } from './QuoteStyle';+import { stringLiteral } from './StringLiteralType';+import { Writer } from './Writer';++describe('QuoteStyle', () => {+ describe('escapeStringContent', () => {+ it('should format with double quotes', () => {+ expect(escapeStringContent('hello', QuoteStyle.Double)).toBe('"hello"');+ expect(escapeStringContent('hello "world"', QuoteStyle.Double)).toBe('"hello \\"world\\""');+ expect(escapeStringContent("hello 'world'", QuoteStyle.Double)).toBe('"hello \'world\'"');+ });++ it('should format with single quotes', () => {+ expect(escapeStringContent('hello', QuoteStyle.Single)).toBe("'hello'");+ expect(escapeStringContent("hello 'world'", QuoteStyle.Single)).toBe("'hello \\'world\\''");+ expect(escapeStringContent('hello "world"', QuoteStyle.Single)).toBe('\'hello "world"\'');+ });++ it('should format with backticks', () => {+ expect(escapeStringContent('hello', QuoteStyle.Backtick)).toBe('`hello`');+ expect(escapeStringContent('hello `world`', QuoteStyle.Backtick)).toBe('`hello \\`world\\``');+ expect(escapeStringContent('hello $world', QuoteStyle.Backtick)).toBe('`hello \\$world`');+ });++ it('should handle backslashes correctly', () => {+ expect(escapeStringContent('hello\\world', QuoteStyle.Double)).toBe('"hello\\\\world"');+ expect(escapeStringContent('hello\\world', QuoteStyle.Single)).toBe("'hello\\\\world'");+ expect(escapeStringContent('hello\\world', QuoteStyle.Backtick)).toBe('`hello\\\\world`');+ });+ });++ describe('StringLiteralType with different quote styles', () => {+ it('should use double quotes by default', () => {+ const literal = stringLiteral('hello world');+ const writer = new Writer(0, undefined);+ literal.write(writer);+ expect(writer.toString()).toBe('"hello world"');+ });++ it('should use single quotes when configured', () => {+ const literal = stringLiteral('hello world');+ const writer = new Writer(0, undefined, { quoteStyle: QuoteStyle.Single });+ literal.write(writer);+ expect(writer.toString()).toBe("'hello world'");+ });++ it('should use backticks when configured', () => {+ const literal = stringLiteral('hello world');+ const writer = new Writer(0, undefined, { quoteStyle: QuoteStyle.Backtick });+ literal.write(writer);+ expect(writer.toString()).toBe('`hello world`');+ });++ it('should handle quotes in content correctly', () => {+ const literal = stringLiteral('hello "world"');++ // Double quotes - content quotes are escaped+ const doubleWriter = new Writer(0, undefined, { quoteStyle: QuoteStyle.Double });+ literal.write(doubleWriter);+ expect(doubleWriter.toString()).toBe('"hello \\"world\\""');++ // Single quotes - content quotes are not escaped+ const singleWriter = new Writer(0, undefined, { quoteStyle: QuoteStyle.Single });+ literal.write(singleWriter);+ expect(singleWriter.toString()).toBe('\'hello "world"\'');+ });++ it('should handle single quotes in content correctly', () => {+ const literal = stringLiteral("hello 'world'");++ // Double quotes - content quotes are not escaped+ const doubleWriter = new Writer(0, undefined, { quoteStyle: QuoteStyle.Double });+ literal.write(doubleWriter);+ expect(doubleWriter.toString()).toBe('"hello \'world\'"');++ // Single quotes - content quotes are escaped+ const singleWriter = new Writer(0, undefined, { quoteStyle: QuoteStyle.Single });+ literal.write(singleWriter);+ expect(singleWriter.toString()).toBe("'hello \\'world\\''");+ });++ it('should handle special characters in backticks', () => {+ const literal = stringLiteral('hello `$world`');+ const writer = new Writer(0, undefined, { quoteStyle: QuoteStyle.Backtick });+ literal.write(writer);+ expect(writer.toString()).toBe('`hello \\`\\$world\\``');+ });+ });+});diff --git a/ts/packages/ts-builders/src/QuoteStyle.ts b/ts/packages/ts-builders/src/QuoteStyle.tsnew file mode 100644index 000000000..0b43bb9fd--- /dev/null+++ b/ts/packages/ts-builders/src/QuoteStyle.ts@@ -0,0 +1,46 @@+/**+ * Configuration for quote styles in string literals+ */++export enum QuoteStyle {+ /** Use double quotes: "hello" */+ Double = 'double',+ /** Use single quotes: 'hello' */+ Single = 'single',+ /** Use backticks for template literals: `hello` */+ Backtick = 'backtick',+}++/**+ * Configuration options for code generation+ */+export interface FormattingOptions {+ /** Quote style for string literals */+ quoteStyle: QuoteStyle;+}++/**+ * Default formatting options+ */+export const DEFAULT_FORMATTING_OPTIONS: FormattingOptions = {+ quoteStyle: QuoteStyle.Double,+};++/**+ * Escapes a string content for the specified quote style+ */+export function escapeStringContent(content: string, quoteStyle: QuoteStyle): string {+ switch (quoteStyle) {+ case QuoteStyle.Double:+ return JSON.stringify(content);++ case QuoteStyle.Single:+ return "'" + content.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";++ case QuoteStyle.Backtick:+ return '`' + content.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$/g, '\\$') + '`';++ default:+ throw new Error(`Unsupported quote style: ${quoteStyle}`);+ }+}diff --git a/ts/packages/ts-builders/src/StringLiteralType.ts b/ts/packages/ts-builders/src/StringLiteralType.tsnew file mode 100644index 000000000..61ea22866--- /dev/null+++ b/ts/packages/ts-builders/src/StringLiteralType.ts@@ -0,0 +1,39 @@+import { TypeBuilder } from './TypeBuilder';+import { ValueBuilder } from './ValueBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';+import { escapeStringContent } from './QuoteStyle';++export class StringLiteralType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.Atomic;++ constructor(readonly content: string) {+ super();+ }++ write(writer: Writer): void {+ const escaped = escapeStringContent(this.content, writer.formattingOptions.quoteStyle);+ writer.write(escaped);+ }++ asValue(): StringLiteralValue {+ return new StringLiteralValue(this);+ }+}++export class StringLiteralValue extends ValueBuilder {+ #type: StringLiteralType;++ constructor(type: StringLiteralType) {+ super();+ this.#type = type;+ }++ override write(writer: Writer): void {+ writer.write(this.#type);+ }+}++export function stringLiteral(content: string) {+ return new StringLiteralType(content);+}diff --git a/ts/packages/ts-builders/src/TupleType.test.ts b/ts/packages/ts-builders/src/TupleType.test.tsnew file mode 100644index 000000000..d22145bbd--- /dev/null+++ b/ts/packages/ts-builders/src/TupleType.test.ts@@ -0,0 +1,25 @@+import { expect, test } from 'vitest';++import { namedType } from './NamedType';+import { stringify } from './stringify';+import { tupleItem, tupleType } from './TupleType';++test('empty', () => {+ const tuple = tupleType();+ expect(stringify(tuple)).toMatchInlineSnapshot(`"[]"`);+});++test('one item', () => {+ const tuple = tupleType().add(namedType('A'));+ expect(stringify(tuple)).toMatchInlineSnapshot(`"[A]"`);+});++test('with named item', () => {+ const tuple = tupleType().add(tupleItem(namedType('A')).setName('foo'));+ expect(stringify(tuple)).toMatchInlineSnapshot(`"[foo: A]"`);+});++test('multiple items', () => {+ const tuple = tupleType().add(namedType('A')).add(namedType('B')).add(namedType('C'));+ expect(stringify(tuple)).toMatchInlineSnapshot(`"[A, B, C]"`);+});diff --git a/ts/packages/ts-builders/src/TupleType.ts b/ts/packages/ts-builders/src/TupleType.tsnew file mode 100644index 000000000..ff3c560b2--- /dev/null+++ b/ts/packages/ts-builders/src/TupleType.ts@@ -0,0 +1,46 @@+import type { BasicBuilder } from './BasicBuilder';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence } from './OperatorPrecedence';++export class TupleItem implements BasicBuilder {+ private name: string | undefined;+ constructor(readonly type: TypeBuilder) {}++ setName(name: string) {+ this.name = name;+ return this;+ }++ write(writer: Writer<undefined>): void {+ if (this.name) {+ writer.write(this.name).write(': ');+ }+ writer.write(this.type);+ }+}++export class TupleType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.TupleType;+ readonly items: TupleItem[] = [];++ add(item: TypeBuilder | TupleItem) {+ if (item instanceof TypeBuilder) {+ item = new TupleItem(item);+ }+ this.items.push(item);+ return this;+ }++ override write(writer: Writer): void {+ writer.write('[').writeJoined(', ', this.items).write(']');+ }+}++export function tupleType() {+ return new TupleType();+}++export function tupleItem(type: TypeBuilder) {+ return new TupleItem(type);+}diff --git a/ts/packages/ts-builders/src/TypeBuilder.ts b/ts/packages/ts-builders/src/TypeBuilder.tsnew file mode 100644index 000000000..aa171622d--- /dev/null+++ b/ts/packages/ts-builders/src/TypeBuilder.ts@@ -0,0 +1,33 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence, TypeContext, needsParentheses } from './OperatorPrecedence';++export abstract class TypeBuilder implements BasicBuilder {+ /**+ * The precedence level of this type builder.+ * Used to determine when parentheses are needed automatically.+ */+ abstract readonly precedence: OperatorPrecedence;++ abstract write(writer: Writer): void;++ /**+ * Writes this type with parentheses if needed in the given context+ */+ writeInContext(writer: Writer, context: TypeContext): void {+ if (needsParentheses(this.precedence, context)) {+ writer.write('(');+ this.write(writer);+ writer.write(')');+ } else {+ this.write(writer);+ }+ }++ /**+ * @deprecated Use writeInContext with TypeContext.IndexAccess instead+ */+ writeIndexed(writer: Writer) {+ this.writeInContext(writer, TypeContext.IndexAccess);+ }+}diff --git a/ts/packages/ts-builders/src/TypeDeclaration.test.ts b/ts/packages/ts-builders/src/TypeDeclaration.test.tsnew file mode 100644index 000000000..a2544ef9f--- /dev/null+++ b/ts/packages/ts-builders/src/TypeDeclaration.test.ts@@ -0,0 +1,35 @@+import { expect, test } from 'vitest';++import { docComment } from './DocComment';+import { genericParameter } from './GenericParameter';+import { namedType } from './NamedType';+import { stringify } from './stringify';+import { typeDeclaration } from './TypeDeclaration';++const A = namedType('A');++test('basic', () => {+ expect(stringify(typeDeclaration('B', A))).toMatchInlineSnapshot(`"type B = A"`);+});++test('with doc comment', () => {+ const decl = typeDeclaration('B', A).setDocComment(docComment('Type for stuff'));+ expect(stringify(decl)).toMatchInlineSnapshot(`+ "/**+ * Type for stuff+ */+ type B = A"+ `);+});++test('with generic parameters', () => {+ const decl = typeDeclaration('B', A).addGenericParameter(genericParameter('T'));+ expect(stringify(decl)).toMatchInlineSnapshot(`"type B<T> = A"`);+});++test('with multiple generic parameters', () => {+ const decl = typeDeclaration('B', A)+ .addGenericParameter(genericParameter('T'))+ .addGenericParameter(genericParameter('U'));+ expect(stringify(decl)).toMatchInlineSnapshot(`"type B<T, U> = A"`);+});diff --git a/ts/packages/ts-builders/src/TypeDeclaration.ts b/ts/packages/ts-builders/src/TypeDeclaration.tsnew file mode 100644index 000000000..171202dc5--- /dev/null+++ b/ts/packages/ts-builders/src/TypeDeclaration.ts@@ -0,0 +1,48 @@+import type { BasicBuilder } from './BasicBuilder';+import { DocComment } from './DocComment';+import { GenericParameter } from './GenericParameter';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';++export class TypeDeclaration<InnerType extends TypeBuilder = TypeBuilder> implements BasicBuilder {+ private genericParameters: GenericParameter[] = [];+ private docComment?: DocComment;++ constructor(+ public name: string,+ readonly type: InnerType+ ) {}++ addGenericParameter(param: GenericParameter): this {+ this.genericParameters.push(param);+ return this;+ }++ setName(name: string) {+ this.name = name;+ return this;+ }++ setDocComment(docComment: DocComment): this {+ this.docComment = docComment;+ return this;+ }++ write(writer: Writer): void {+ if (this.docComment) {+ writer.write(this.docComment);+ }+ writer.write('type ').write(this.name);+ if (this.genericParameters.length > 0) {+ writer.write('<').writeJoined(', ', this.genericParameters).write('>');+ }+ writer.write(' = ').write(this.type);+ }+}++export function typeDeclaration<InnerType extends TypeBuilder = TypeBuilder>(+ name: string,+ type: InnerType+) {+ return new TypeDeclaration(name, type);+}diff --git a/ts/packages/ts-builders/src/TypeOf.ts b/ts/packages/ts-builders/src/TypeOf.tsnew file mode 100644index 000000000..9aac99da3--- /dev/null+++ b/ts/packages/ts-builders/src/TypeOf.ts@@ -0,0 +1,20 @@+import { TypeBuilder } from './TypeBuilder';+import type { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class TypeofType extends TypeBuilder {+ readonly precedence = OperatorPrecedence.TypeofType;++ constructor(public baseType: TypeBuilder) {+ super();+ }++ write(writer: Writer): void {+ writer.write(`typeof `);+ this.baseType.writeInContext(writer, TypeContext.TypeofOperand);+ }+}++export function typeOfType(baseType: TypeBuilder): TypeofType {+ return new TypeofType(baseType);+}diff --git a/ts/packages/ts-builders/src/UnionType.multiline.test.ts b/ts/packages/ts-builders/src/UnionType.multiline.test.tsnew file mode 100644index 000000000..9a5d943f0--- /dev/null+++ b/ts/packages/ts-builders/src/UnionType.multiline.test.ts@@ -0,0 +1,59 @@+import { describe, it, expect } from 'vitest';+import { unionType } from './UnionType';+import { namedType } from './NamedType';+import { stringLiteral } from './StringLiteralType';+import { Writer } from './Writer';++describe('UnionType multiline formatting', () => {+ it('should format simple union types in multiline style', () => {+ const union = unionType([namedType('string'), namedType('number'), namedType('boolean')]);++ const writer = new Writer(0, undefined);+ union.formatMultiline().write(writer);++ expect(writer.toString()).toBe(['', ' | string', ' | number', ' | boolean'].join('\n'));+ });++ it('should format string literal union types in multiline style', () => {+ const union = unionType([+ stringLiteral('success'),+ stringLiteral('error'),+ stringLiteral('pending'),+ ]);++ const writer = new Writer(0, undefined);+ union.formatMultiline().write(writer);++ expect(writer.toString()).toBe(+ ['', ' | "success"', ' | "error"', ' | "pending"'].join('\n')+ );+ });++ it('should still format inline when multiline is not enabled', () => {+ const union = unionType([namedType('string'), namedType('number'), namedType('boolean')]);++ const writer = new Writer(0, undefined);+ union.write(writer);++ expect(writer.toString()).toBe('string | number | boolean');+ });++ it('should handle single variant union in multiline', () => {+ const union = unionType(namedType('string'));++ const writer = new Writer(0, undefined);+ union.formatMultiline().write(writer);++ expect(writer.toString()).toBe(['', ' | string'].join('\n'));+ });++ it('should handle empty variants gracefully', () => {+ const union = unionType([namedType('string')]);+ union.variants.length = 0; // Force empty for edge case test++ const writer = new Writer(0, undefined);+ union.formatMultiline().write(writer);++ expect(writer.toString()).toBe('');+ });+});diff --git a/ts/packages/ts-builders/src/UnionType.test.ts b/ts/packages/ts-builders/src/UnionType.test.tsnew file mode 100644index 000000000..b07ea343a--- /dev/null+++ b/ts/packages/ts-builders/src/UnionType.test.ts@@ -0,0 +1,39 @@+import { expect, test } from 'vitest';++import { array } from './ArrayType';+import { functionType } from './FunctionType';+import { namedType } from './NamedType';+import { stringify } from './stringify';+import { unionType } from './UnionType';++const A = namedType('A');+const B = namedType('B');++test('one type', () => {+ expect(stringify(unionType(A))).toMatchInlineSnapshot(`"A"`);+});++test('multiple types', () => {+ expect(stringify(unionType(A).addVariant(B))).toMatchInlineSnapshot(`"A | B"`);+});++test('from array', () => {+ expect(stringify(unionType([A, B]))).toMatchInlineSnapshot(`"A | B"`);+});++test('with function type', () => {+ expect(stringify(unionType([A, B, functionType()]))).toMatchInlineSnapshot(+ `"A | B | (() => void)"`+ );+});++test('fails with empty array', () => {+ expect(() => unionType([])).toThrowErrorMatchingInlineSnapshot(+ `[TypeError: Union types array can not be empty]`+ );+});++test('mapVariants', () => {+ const union = unionType([A, B]).mapVariants(array);+ expect(stringify(union)).toMatchInlineSnapshot(`"A[] | B[]"`);+});diff --git a/ts/packages/ts-builders/src/UnionType.ts b/ts/packages/ts-builders/src/UnionType.tsnew file mode 100644index 000000000..72660eaf0--- /dev/null+++ b/ts/packages/ts-builders/src/UnionType.ts@@ -0,0 +1,92 @@+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';+import { OperatorPrecedence, TypeContext } from './OperatorPrecedence';++export class UnionType<VariantType extends TypeBuilder = TypeBuilder> extends TypeBuilder {+ readonly precedence = OperatorPrecedence.Union;+ readonly variants: VariantType[];+ private multiline = false;++ constructor(firstType: VariantType) {+ super();+ this.variants = [firstType];+ }++ addVariant(variant: VariantType) {+ this.variants.push(variant);+ return this;+ }++ addVariants(variants: VariantType[]) {+ for (const variant of variants) {+ this.addVariant(variant);+ }+ return this;+ }++ /**+ * Format this union type in multi-line style:+ * type SomeUnion =+ * | UnionVariantA+ * | UnionVariantB+ * | UnionVariantC;+ */+ formatMultiline() {+ this.multiline = true;+ return this;+ }++ write(writer: Writer): void {+ if (this.multiline) {+ this.writeMultiline(writer);+ } else {+ this.writeInline(writer);+ }+ }++ private writeInline(writer: Writer): void {+ writer.writeJoined(' | ', this.variants, (variant, writer) => {+ variant.writeInContext(writer, TypeContext.UnionMember);+ });+ }++ private writeMultiline(writer: Writer): void {+ if (this.variants.length === 0) {+ return;+ }++ const nestedWriter = writer.writeLine('').indent();++ // All variants with pipe symbol and indentation+ for (let i = 0; i < this.variants.length; i++) {+ if (i > 0) {+ nestedWriter.writeLine('');+ }++ nestedWriter.write('| ');+ this.variants[i].writeInContext(nestedWriter, TypeContext.UnionMember);+ }+ }++ mapVariants<NewVariantType extends TypeBuilder>(+ callback: (type: VariantType) => NewVariantType+ ): UnionType<NewVariantType> {+ return unionType(this.variants.map(v => callback(v)));+ }+}++export function unionType<VariantType extends TypeBuilder = TypeBuilder>(+ types: VariantType[] | VariantType+) {+ if (Array.isArray(types)) {+ if (types.length === 0) {+ throw new TypeError('Union types array can not be empty');+ }+ const union = new UnionType(types[0]);+ for (let i = 1; i < types.length; i++) {+ union.addVariant(types[i]);+ }+ return union;+ }+ return new UnionType(types);+}diff --git a/ts/packages/ts-builders/src/ValueBuilder.ts b/ts/packages/ts-builders/src/ValueBuilder.tsnew file mode 100644index 000000000..2726e9cfb--- /dev/null+++ b/ts/packages/ts-builders/src/ValueBuilder.ts@@ -0,0 +1,27 @@+import type { BasicBuilder } from './BasicBuilder';+import { TypeBuilder } from './TypeBuilder';+import { Writer } from './Writer';++export abstract class ValueBuilder implements BasicBuilder {+ as(type: TypeBuilder): TypeAssertion {+ return new TypeAssertion(this, type);+ }++ abstract write(writer: Writer<undefined>): void;+}++// Must be in the same file due to a circular dependency+export class TypeAssertion extends ValueBuilder {+ #value: ValueBuilder;+ #type: TypeBuilder;++ constructor(value: ValueBuilder, type: TypeBuilder) {+ super();+ this.#value = value;+ this.#type = type;+ }++ override write(writer: Writer): void {+ writer.write(this.#value).write(' as ').write(this.#type);+ }+}diff --git a/ts/packages/ts-builders/src/WellKnownSymbol.ts b/ts/packages/ts-builders/src/WellKnownSymbol.tsnew file mode 100644index 000000000..24b51e5dc--- /dev/null+++ b/ts/packages/ts-builders/src/WellKnownSymbol.ts@@ -0,0 +1,15 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';++export class WellKnownSymbol implements BasicBuilder {+ constructor(readonly name: string) {}+ write(writer: Writer<undefined>): void {+ writer.write('Symbol.').write(this.name);+ }+}++export function wellKnownSymbol(name: string) {+ return new WellKnownSymbol(name);+}++export const toStringTag = wellKnownSymbol('toStringTag');diff --git a/ts/packages/ts-builders/src/Writer.test.ts b/ts/packages/ts-builders/src/Writer.test.tsnew file mode 100644index 000000000..06df95e2d--- /dev/null+++ b/ts/packages/ts-builders/src/Writer.test.ts@@ -0,0 +1,123 @@+import { expect, test } from 'vitest';++import { Writer } from './Writer';++test('write string', () => {+ const writer = new Writer(0, undefined);+ writer.write('A').write('B').write('C');+ expect(writer.toString()).toBe('ABC');+});++test('write builder', () => {+ const builder = {+ write(writer: Writer) {+ writer.write('hello from builder');+ },+ };+ const writer = new Writer(0, undefined);+ writer.write(builder);+ expect(writer.toString()).toBe('hello from builder');+});++test('newLine', () => {+ const writer = new Writer(0, undefined);+ writer.newLine();+ expect(writer.toString()).toBe('\n');+});++test('writeLine', () => {+ const writer = new Writer(0, undefined);+ writer.writeLine('A').writeLine('B').writeLine('C');+ expect(writer.toString()).toBe('A\nB\nC\n');+});++test('writeJoined with strings', () => {+ const writer = new Writer(0, undefined);+ writer.writeJoined(', ', ['A', 'B', 'C']);+ expect(writer.toString()).toBe('A, B, C');+});++test('writeJoined with builder values', () => {+ const writer = new Writer(0, undefined);++ const builder = {+ write(writer: Writer) {+ writer.write('builder');+ },+ };+ writer.writeJoined(', ', [builder, builder, builder]);+ expect(writer.toString()).toBe('builder, builder, builder');+});++test('writeJoined with builder separator', () => {+ const writer = new Writer(0, undefined);++ const separator = {+ write(writer: Writer) {+ writer.write('|');+ },+ };+ writer.writeJoined(separator, ['A', 'B', 'C']);+ expect(writer.toString()).toBe('A|B|C');+});++test('writeJoined empty', () => {+ const writer = new Writer(0, undefined);+ writer.writeJoined(', ', []);+ expect(writer.toString()).toBe('');+});++test('indent', () => {+ const writer = new Writer(0, undefined);+ writer.indent().write('A');+ expect(writer.toString()).toBe(' A');+});++test('indent + unindent', () => {+ const writer = new Writer(0, undefined);+ writer.writeLine('A').indent().writeLine('B').unindent().writeLine('C');+ expect(writer.toString()).toBe('A\n B\nC\n');+});++test('unindent beyond 0', () => {+ const writer = new Writer(0, undefined);+ writer.unindent().unindent().write('A');+ expect(writer.toString()).toBe('A');+});++test('withIndent', () => {+ const writer = new Writer(0, undefined);+ writer+ .writeLine('A')+ .withIndent(() => writer.writeLine('B'))+ .writeLine('C');+ expect(writer.toString()).toBe('A\n B\nC\n');+});++test('after next newline callback', () => {+ const writer = new Writer(0, undefined);+ writer.afterNextNewline(() => {+ writer.writeLine('---');+ });+ writer.writeLine('foo');+ writer.writeLine('bar');+ expect(writer.toString()).toBe('foo\n---\nbar\n');+});++test('margin symbol', () => {+ const writer = new Writer(0, undefined);+ writer+ .writeLine('{')+ .withIndent(() => {+ writer.addMarginSymbol('+').writeLine('foo').writeLine('bar');+ })+ .writeLine('}');++ expect(writer.toString()).toMatchInlineSnapshot(`+ "{+ + foo+ bar+ }+ "+ `);+});diff --git a/ts/packages/ts-builders/src/Writer.ts b/ts/packages/ts-builders/src/Writer.tsnew file mode 100644index 000000000..73b4ea966--- /dev/null+++ b/ts/packages/ts-builders/src/Writer.ts@@ -0,0 +1,179 @@+import type { BasicBuilder } from './BasicBuilder';+import type { FormattingOptions } from './QuoteStyle';+import { DEFAULT_FORMATTING_OPTIONS } from './QuoteStyle';++export const INDENT_SIZE = 2;+/**+ * Helper class for building long multi-line formatted strings from building blocks.+ * Can use either plain strings or `Builder` objects, that would encapsulate formatting logic.+ */+export class Writer<ContextType = undefined> {+ private lines: string[] = [];+ private currentLine = '';+ private currentIndent = 0;+ private marginSymbol?: string;+ private afterNextNewLineCallback?: () => void;+ readonly formattingOptions: FormattingOptions;++ constructor(+ startingIndent = 0,+ readonly context: ContextType,+ formattingOptions: Partial<FormattingOptions> = {}+ ) {+ this.currentIndent = startingIndent;+ this.formattingOptions = { ...DEFAULT_FORMATTING_OPTIONS, ...formattingOptions };+ }++ /**+ * Adds provided value to the current line. Does not end the line.+ *+ * @param value+ * @returns+ */+ write(value: string | BasicBuilder<ContextType>): this {+ if (typeof value === 'string') {+ this.currentLine += value;+ } else {+ value.write(this);+ }+ return this;+ }++ /**+ * Adds several `values` to the current line, separated by `separator`. Both values and separator+ * can also be `Builder` instances for more advanced formatting.+ *+ * @param separator+ * @param values+ * @param writeItem allow to customize how individual item is written+ * @returns+ */+ writeJoined<T extends string | BasicBuilder<ContextType>>(+ separator: string | BasicBuilder<ContextType>,+ values: T[],+ writeItem: (item: T, writer: this) => void = (item, w) => w.write(item)+ ): this {+ const last = values.length - 1;+ for (let i = 0; i < values.length; i++) {+ writeItem(values[i], this);+ if (i !== last) {+ this.write(separator);+ }+ }+ return this;+ }++ /**+ * Adds a string to current line, flushes current line and starts a new line.+ * @param line+ * @returns+ */+ writeLine(line: string | BasicBuilder<ContextType>): this {+ return this.write(line).newLine();+ }++ /**+ * Flushes current line and starts a new line. New line starts at previously configured indentation level+ * @returns+ */+ newLine(): this {+ this.lines.push(this.indentedCurrentLine());+ this.currentLine = '';+ this.marginSymbol = undefined;++ const afterNextNewLineCallback = this.afterNextNewLineCallback;+ this.afterNextNewLineCallback = undefined;+ afterNextNewLineCallback?.();+ return this;+ }++ /**+ * Increases indentation level by 1, calls provided callback and then decreases indentation again.+ * Could be used for writing indented blocks of text:+ *+ * @example+ * ```ts+ * writer+ * .writeLine('{')+ * .withIndent(() => {+ * writer.writeLine('foo: 123');+ * writer.writeLine('bar: 456');+ * })+ * .writeLine('}')+ * ```+ * @param callback+ * @returns+ */+ withIndent(callback: (writer: this) => void): this {+ this.indent();+ callback(this);+ this.unindent();+ return this;+ }++ /**+ * Calls provided callback next time when new line is started.+ * Callback is called after old line have already been flushed and a new+ * line have been started. Can be used for adding "between the lines" decorations,+ * such as underlines.+ *+ * @param callback+ * @returns+ */+ afterNextNewline(callback: () => void) {+ this.afterNextNewLineCallback = callback;+ return this;+ }++ /**+ * Increases indentation level of the current line by 1+ * @returns+ */+ indent(): this {+ this.currentIndent++;+ return this;+ }++ /**+ * Decreases indentation level of the current line by 1, if it is possible+ * @returns+ */+ unindent(): this {+ if (this.currentIndent > 0) {+ this.currentIndent--;+ }+ return this;+ }++ /**+ * Adds a symbol, that will replace the first character of the current line (including indentation)+ * when it is flushed. Can be used for adding markers to the line.+ *+ * Note: if indentation level of the line is 0, it will replace the first actually printed character+ * of the line. Use with caution.+ * @param symbol+ * @returns+ */+ addMarginSymbol(symbol: string): this {+ this.marginSymbol = symbol;+ return this;+ }++ toString() {+ return this.lines.concat(this.indentedCurrentLine()).join('\n');+ }++ getCurrentLineLength() {+ return this.currentLine.length;+ }++ private indentedCurrentLine(): string {+ const line = this.currentLine.padStart(+ this.currentLine.length + INDENT_SIZE * this.currentIndent+ );+ if (this.marginSymbol) {+ return this.marginSymbol + line.slice(1);+ }+ return line;+ }+}diff --git a/ts/packages/ts-builders/src/helpers.ts b/ts/packages/ts-builders/src/helpers.tsnew file mode 100644index 000000000..1b6fb089c--- /dev/null+++ b/ts/packages/ts-builders/src/helpers.ts@@ -0,0 +1,6 @@+import { NamedType, namedType } from './NamedType';+import { TypeBuilder } from './TypeBuilder';++export function omit(type: TypeBuilder, keyType: TypeBuilder): NamedType {+ return namedType('Omit').addGenericArgument(type).addGenericArgument(keyType);+}diff --git a/ts/packages/ts-builders/src/index.ts b/ts/packages/ts-builders/src/index.tsnew file mode 100644index 000000000..e63abc255--- /dev/null+++ b/ts/packages/ts-builders/src/index.ts@@ -0,0 +1,42 @@+export * from './AnyDeclarationBuilder';+export * from './ArraySpread';+export * from './ArrayType';+export * from './BasicBuilder';+export * from './Class';+export * from './ConstDeclaration';+export * from './DocComment';+export * from './Export';+export * from './ExportFrom';+export * from './File';+export * from './FunctionCall';+export * from './FunctionType';+export * from './GenericParameter';+export * from './helpers';+export * from './Import';+export * from './Interface';+export * from './KeyofType';+export * from './KeyType';+export * from './Method';+export * from './NamedType';+export * from './NamedValue';+export * from './NamespaceDeclaration';+export * from './ObjectType';+export * from './ObjectValue';+export * from './OperatorPrecedence';+export * from './Parameter';+export * from './PrimitiveType';+export * from './Property';+export * from './PropertyValue';+export * from './QuoteStyle';+export * from './stringify';+export * from './StringLiteralType';+export * from './TupleType';+export * from './TypeBuilder';+export * from './TypeDeclaration';+export * from './TypeOf';+export * from './UnionType';+export * from './ValueBuilder';+export * from './WellKnownSymbol';+export * from './Writer';++export { isValidJsIdentifier } from './isValidJsIdentifier';diff --git a/ts/packages/ts-builders/src/isValidJsIdentifier.ts b/ts/packages/ts-builders/src/isValidJsIdentifier.tsnew file mode 100644index 000000000..e81d85337--- /dev/null+++ b/ts/packages/ts-builders/src/isValidJsIdentifier.ts@@ -0,0 +1,5 @@+import { isIdentifierName } from '@babel/helper-validator-identifier';++export function isValidJsIdentifier(name: string): boolean {+ return isIdentifierName(name);+}diff --git a/ts/packages/ts-builders/src/stringify.ts b/ts/packages/ts-builders/src/stringify.tsnew file mode 100644index 000000000..0c4586b27--- /dev/null+++ b/ts/packages/ts-builders/src/stringify.ts@@ -0,0 +1,30 @@+import type { BasicBuilder } from './BasicBuilder';+import { Writer } from './Writer';++export function assertNever(_arg: never, errorMessage: string): never {+ throw new Error(errorMessage);+}++type StringifyOptions = {+ indentLevel?: number;+ newLine?: 'none' | 'leading' | 'trailing' | 'both';+};++export function stringify(+ builder: BasicBuilder,+ { indentLevel = 0, newLine = 'none' }: StringifyOptions = {}+) {+ const str = new Writer(indentLevel, undefined).write(builder).toString();+ switch (newLine) {+ case 'none':+ return str;+ case 'leading':+ return '\n' + str;+ case 'trailing':+ return str + '\n';+ case 'both':+ return '\n' + str + '\n';+ default:+ assertNever(newLine, 'Unexpected value');+ }+}diff --git a/ts/packages/ts-builders/tsconfig.json b/ts/packages/ts-builders/tsconfig.jsonnew file mode 100644index 000000000..1cb112547--- /dev/null+++ b/ts/packages/ts-builders/tsconfig.json@@ -0,0 +1,8 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src"]+}diff --git a/ts/packages/ts-builders/tsconfig.options.json b/ts/packages/ts-builders/tsconfig.options.jsonnew file mode 100644index 000000000..cca3ec370--- /dev/null+++ b/ts/packages/ts-builders/tsconfig.options.json@@ -0,0 +1,23 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "declaration": true,+ "outDir": "./dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "node",+ "skipLibCheck": true,+ "resolveJsonModule": true,+ "verbatimModuleSyntax": true,+ "pretty": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUnusedLocals": false,+ "noUnusedParameters": false+ },+ "include": ["src"],+ "exclude": ["**/dist", "test/__fixtures__/**"]+}diff --git a/ts/packages/ts-builders/tsconfig.src.json b/ts/packages/ts-builders/tsconfig.src.jsonnew file mode 100644index 000000000..d8d650fbb--- /dev/null+++ b/ts/packages/ts-builders/tsconfig.src.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "outDir": "./dist",+ "rootDir": ".",+ "paths": {+ "src/*": ["./src/*"]+ }+ },+ "include": ["src"],+ "exclude": ["src/**/*.test.ts"]+}diff --git a/ts/packages/ts-builders/tsconfig.test.json b/ts/packages/ts-builders/tsconfig.test.jsonnew file mode 100644index 000000000..1b2ad574d--- /dev/null+++ b/ts/packages/ts-builders/tsconfig.test.json@@ -0,0 +1,12 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": ".",+ "paths": {+ "src/*": ["./src/*"],+ "test/*": ["./test/*"]+ }+ },+ "include": ["test"]+}diff --git a/ts/packages/ts-builders/tsup.config.ts b/ts/packages/ts-builders/tsup.config.tsnew file mode 100644index 000000000..6f7c33d6f--- /dev/null+++ b/ts/packages/ts-builders/tsup.config.ts@@ -0,0 +1,11 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: ['src/index.ts'],+ format: ['esm'],+ dts: true,+ clean: true,+ minify: false,+ outDir: 'dist',+ tsconfig: './tsconfig.src.json',+});